加入支持多线程(线程池)
package com.zibra.server.thread;
import java.net.Socket;
public class SocketThread implements Runnable {
// 线程参数
private Socket socket;
public SocketThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
// 执行业务代码
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 断开连接
if (socket != null) {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
服务器的主线程负责接收客户的连接, 每次接收到一个客户连接, 就会创建一个工作线程, 由它负责与客户的通信.
package com.zibra.server;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.zibra.server.thread.SocketThread;
public class Server {
private static ExecutorService executoService;
/*
* 每个cpu启动线程条数
*/
private final static int POOL_SIZE = 10;
/*
* 端口连接超时
*/
private final static int SOCKET_TIME_OUT = 5000000;
/*
* 服务器地址
*/
private final static String HOST_NAME = "127.0.0.1";
/*
* 端口连接超时
*/
private final static int SERVER_PORT = 9999;
/*
* 端口访问队列长度
*/
private final static int BACK_LOG = 10;
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket();
serverSocket.setSoTimeout(SOCKET_TIME_OUT);
// 邦定本机ip:127.0.0.1 端口:9999 连接队列:10
serverSocket.bind(new InetSocketAddress(HOST_NAME, SERVER_PORT), BACK_LOG);
// 创建线程池
// Runtime 的 availablePocessors() 方法返回当前系统的CPU 的数目
// 系统的CPU 越多, 线程池中工作线程的数目也越多
executoService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
while (serverSocket.isBound() && !serverSocket.isClosed()) {
try {
try {
// 把与可以通信的任务交给线程池
Socket socket = serverSocket.accept();
executoService.execute(new SocketThread(socket));
} catch (SocketException socketException) {
if ("Connection reset by peer".equals(socketException.getMessage())) {
socketException.printStackTrace();
} else {
throw socketException;
}
}
} catch (Exception e) {
e.printStackTrace();
if (null != serverSocket && !serverSocket.isClosed()) {
serverSocket.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.exit(1);
}
}