socket连接池
SocketServerPool 含有两个参数 listenPort , maxConnection 。分别表示监听端口和最大连接数。
函数setHandlers() 里面初始化了5个PoolConnectionHandler的线程,表示池中能同时最大处理5个连接。
/**
* @author jake1036
* 2010.7.16 20:05
* socket连接池类
*/
package cn.bupt.net;
import java.io.*;
import java.net.*;
/**
* @author jake1036
*
*/
public class SocketServerPool {
/*最大连接和监听端口*/
private int maxConnections ;
private int listenPort ;
public SocketServerPool(int listenPort , int maxConnections){
this.listenPort = listenPort ;
this.maxConnections = maxConnections ;
}
public void acceptConnections(){
try {
ServerSocket serverSocket = new ServerSocket(listenPort , 5) ;
Socket socket= null ;
while(true)
{
socket = serverSocket.accept() ;
PoolConnectionHandler.processRequest(socket) ;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void setHandlers()
{
for(int i = 0 ; i < this.maxConnections ; i++ )
{
PoolConnectionHandler poolHandler = new PoolConnectionHandler() ;
new Thread(poolHandler , "handler" + i).start() ;
}
}
public static void main(String [] args)
{
SocketServerPool pool = new SocketServerPool(8888 , 5) ;
pool.setHandlers() ;
pool.acceptConnections() ;
}
}
温馨提示:内容为网友见解,仅供参考