本文程序摘自:ibm.com/developerworks
使用线程池的好处就不必我多说了,主要是减少socket初始化的代价,这里的描述只设计到服务器的实现,关于客户端的代码和前面多线程服务器相同,可参考:http://blog.csdn.net/notruiyi/archive/2005/10/26/517047.aspx
-------------------------------------------------------------------------------------------------------------
//服务器实现
import java.io.*;
import java.net.*;
import java.util.*;
public class PooledFileServer{
private int maxConnections;//设置的线程数
private int listenPort;//侦听端口号
private ServerSocket serverSocket;
public PooledFileServer(int port , int maxCon){
this.listenPort = port;
this.maxConnections = maxCon;
}
//启动线程池
public void setupHandlers(){
for(int i=0 ; i<maxConnections ; ++i){
//创建PooledConnectionHandle对象,该类实现了runnable接口
PooledConnectionHandle connectionHandle = new PooledConnectionHandle();
//启动线程
new Thread(connectionHandle,"handle"+i).start();
}
}
//开始接收请求
public void acceptConnection(){
try{
ServerSocket server = new ServerSocket(listenPort,5);
Socket IncomingSocket = null;
while(true){
incomingSocket = server.accept();
hancleConnection(incomingSocket);
}
}catch(BindException e){
System.out.println("Unable to bind to port.");
}catch(IOException e){
System.out.println("Unable to init ServerSocket.");
}
}
//处理连接请求,将客户socket传给PooledConnectionHandle的静态方法processRequest,后者将该socket放入请求队列
private void handleConnection(incomingSocket){
PooledConnectionHandle.processRequest(incomingSocket);
}
}
-------------------------------------------------------------------------------------------------------------------------
//连接处理器
import java.io.*;
import java.net.*;
import java.util.*;
public class PooledConnectionHandle implements Runnable{
private Socket socket;
//存放所有请求的socket,使用链表模拟队列
private static List pool = new LinkedList();
public PooledConnectionHandle(){}
//处理文件传输
public void handleConnection(){
try{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader outputReader = new BufferReader(new OutputStreamReader(socket.getOutputStream()));
//获取要读取的文件名
FileReader fileReader = new FileReader(new File(inputReader.readLine()));
BufferedReader bufferedFileReader = new BufferReader(fileReader);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
String line = null;
While((line = bufferFileReader.readLine())!=null)
printWriter.println(line);
fileReader.close();
printWriter.close();
outputReader.close();
}catch(Exception e){
System.out.println("Exception occured when handiling a client connection.");
}
}
//将请求的socket链入请求队列
public static void processRequest(Socket requestSocket){
synchronized(pool){
pool.add(pool.size(),requestSocket)
pool.notifyAll();
}
}
//主线程
public void run(){
while(true){
synchronized(pool){
while(pool.isEmpty()){
try{
pool.wait();
}catch(){
return;
}
}
socket = (Socket)pool.remove(0);
}
handleConnection();
}
}
}