日期:2014-05-20 浏览次数:20733 次
public class Server {
private static Logger logger = Logger.getLogger(Server.class);
private int tryBindTimes = 0; //初始的绑定端口的次数设定为0
private ServerSocket serverSocket; //服务套接字等待对方的连接和文件发送
private ExecutorService executorService; //线程池
private final int POOL_SIZE = 4; //单个CPU的线程池大小
private BaseSock bsock;
public Server() throws Exception{
this.bsock=new BaseSock();
try {
this.bingToServerPort(this.bsock.getPort());
executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
System.out.println("开辟线程数 : " + Runtime.getRuntime().availableProcessors() * POOL_SIZE);
} catch (Exception e) {
logger.info("绑定端口不成功!");
throw new Exception("绑定端口不成功!");
}
}
private void bingToServerPort(int port) throws Exception{
try {
serverSocket = new ServerSocket(port);
//System.out.println(port);
System.out.println("服务启动!");
logger.info("服务启动!");
} catch (Exception e) {
this.tryBindTimes = this.tryBindTimes + 1;
port = port + this.tryBindTimes;
if(this.tryBindTimes >= 20){
logger.info("已经尝试很多次了,但是仍无法绑定到指定的端口!请重新选择绑定的默认端口号!");
throw new Exception("您已经尝试很多次了,但是仍无法绑定到指定的端口!请重新选择绑定的默认端口号");
}
//递归绑定端口
this.bingToServerPort(port);
}
}
//开启服务
public boolean service(){
Socket socket = null;
while (true) {
try {
socket = serverSocket.accept();
executorService.execute(new HandServer(socket));
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
//内部类(继承Runnable),处理数据接收
class HandServer implements Runnable{
private Socket socket;
public HandServer(Socket socket){
this.socket = socket;
}
public void run() {
System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
logger.info("已建立新的连接。");
DataInputStream dis = null;
DataOutputStream dos = null;
.
.
.
//数据接收的部分代码
}
}