1、我贴出的主要是核心代码,有些类为自己定义,并未贴出,大家可以主要看实现思路
2、核心代码
public class Server {
private ServerSocket serverSocket;
private ExecutorService executorService;// 线程池
private boolean isStarted = true;
private Socket socket;
public Server() {
try {
serverSocket = new ServerSocket(Constants.SERVER_PORT);
executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
.availableProcessors() * 50);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
quit();
}
}
public void start(){
System.out.println(MyDate.getDateCN());
while(isStarted){
try {
socket = serverSocket.accept();
String ip = socket.getInetAddress().toString();
System.out.println(MyDate.getDateCN() + " 用户:" + ip + " 已建立连接");
if(socket.isConnected()){
executorService.execute(new SocketToask(socket));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(serverSocket != null){
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private final class SocketToask implements Runnable{
private Socket socket;
private InputThread in;
private OutputThread out;
private OutputThreadMap map;
public SocketToask(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
out = new OutputThread(socket, map);//
// 先实例化写消息线程,(把对应用户的写线程存入map缓存器中)
in = new InputThread(socket, out, map);// 再实例化读消息线程
out.setStart(true);
in.setStart(true);
in.start();
out.start();
}
}
public void quit() {
try {
this.isStarted = false;
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.start();
}
}