思路:采用线程池来解决多个客户端请求,简单的设置线程数可以与CPU核数匹配,过多的线程数空闲会消耗服务器资源。
package com.Lx;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiServer {
public static void main(String[] args) throws IOException {
//线程池中创建一个三线程的服务
ExecutorService es = Executors.newFixedThreadPool(3);
ServerSocket sever = new ServerSocket(111);
System.out.println("服务器开始启动,等待连接。。。");
while (true){
Socket s = sever.accept();
System.out.println(s.getInetAddress().getHostAddress());
es.execute(new UserThread(s));
}
}
}
class UserThread implements Runnable{
private Socket s;
public UserThread(Socket s){
this.s = s;
}
@Override
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintStream ps = new PrintStream(new BufferedOutputStream(s.getOutputStream()));
String info = br.readLine();
System.out.println(info);
ps.println("echo"+info);
ps.flush();
ps.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}