SingleThreaded,MutiThreaded and Thread Pooled Server(1)
大家都知道,线程在Java中是很重要,特别是用在socket编程中。
一般用socket写服务端,都用线程来写。
我们看看只用一条线程实现的服务端主要代码:
[code]
public void run(){
synchronized(this){
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(! isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.") ;
return;
}
throw new RuntimeException(
"Error accepting client connection", e);
}
try {
processClientRequest(clientSocket);
} catch (IOException e) {
//log exception and go on to next request.
}
}
System.out.println("Server Stopped.");
}
private void processClientRequest(Socket clientSocket)throws IOException {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\n<html><body>" +"Singlethreaded Server: " +time +"</body></html>").getBytes());
output.close();
input.close();
System.out.println("Request processed: " + time);
}
[/code]
从代码上可知道服务端一直在执行:
1、等待客户端请求
2、处理客户端请求
3、转回1
大部分Java实现的服务端都是执行这三个步骤。但单线程服务端与多线程服务端的区别在于客户端请求的处理过程是否与接收请求是在同一线程里执行。
如上边的就是单线程服务端。这不是一个好的服务端实现方案:因为只有在serverSocket.accept()时,客户端要连接到这个服务端。 当一个请求处理时间太长时,等待连接的客户端就会掉失。
大家都知道,线程在Java中是很重要,特别是用在socket编程中。
一般用socket写服务端,都用线程来写。
我们看看只用一条线程实现的服务端主要代码:
[code]
public void run(){
synchronized(this){
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(! isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.") ;
return;
}
throw new RuntimeException(
"Error accepting client connection", e);
}
try {
processClientRequest(clientSocket);
} catch (IOException e) {
//log exception and go on to next request.
}
}
System.out.println("Server Stopped.");
}
private void processClientRequest(Socket clientSocket)throws IOException {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\n<html><body>" +"Singlethreaded Server: " +time +"</body></html>").getBytes());
output.close();
input.close();
System.out.println("Request processed: " + time);
}
[/code]
从代码上可知道服务端一直在执行:
1、等待客户端请求
2、处理客户端请求
3、转回1
大部分Java实现的服务端都是执行这三个步骤。但单线程服务端与多线程服务端的区别在于客户端请求的处理过程是否与接收请求是在同一线程里执行。
如上边的就是单线程服务端。这不是一个好的服务端实现方案:因为只有在serverSocket.accept()时,客户端要连接到这个服务端。 当一个请求处理时间太长时,等待连接的客户端就会掉失。