/**
* @Author lyr
* @create 2020/8/7 1:07
*/
public interface EchoServer {
/**
* 开启 port 端口的服务
* @param port
*/
void startServer(int port) throws IOException;
}
public interface EchoClient {
void connect(String ipAddr,int port);
// void send(String requestBody);
// void quit();
}
public class EchoClientIml implements EchoClient {
@Override
public void connect(String ipAddr, int port) {
try {
new Client().connect(ipAddr,port);
} catch (IOException e) {
e.printStackTrace();
}
}
static class Client {
void connect(String ip,int port) throws IOException {
Socket cli = new Socket(ip, port);
BufferedReader in = new BufferedReader(new InputStreamReader(cli.getInputStream()));
// Writer out;
PrintWriter out = new PrintWriter(cli.getOutputStream(),true);
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String me = sc.nextLine();
if(me.equalsIgnoreCase("quit")) {
out.println(me);
System.out.println("连接关闭");
break;
}
out.println(me);
String resp = in.readLine();
System.out.println(String.format("收到回复 [%s]",resp));
}
}
}
public static void main(String[] args) {
new EchoClientIml().connect("127.0.0.1",8888);
}
}
public class EchoServerImpl implements EchoServer {
public static void main(String[] args) throws InterruptedException, IOException {
EchoServer server = new EchoServerImpl();
server.startServer(8888);
// System.out.println("结束");
}
@Override
public void startServer(int port) throws IOException {
ServerSocket serverSocket = new ServerSocket(port);
AtomicInteger num = new AtomicInteger(0);
while (true) {
Socket cli = serverSocket.accept();
new Thread(() -> {
new Server(port, cli, num.incrementAndGet()).start();
}).start();
}
}
private static class Server {
int port;
int id;
Socket cli;
PrintWriter out;
BufferedReader in;
public Server(int port, Socket cli, int id) {
this.port = port;
this.cli = cli;
this.id = id;
}
void start() {
try {
out = new PrintWriter(cli.getOutputStream(), true);
in = new BufferedReader(new UTF8Reader(cli.getInputStream()));
String body = null;
while ((body = in.readLine()) != null) {
if("quit".equalsIgnoreCase(body)) {
in.close();
out.close();
cli.close();
break;
}
System.out.println(String.format("来自用户的数据[%s] %s",id, body));
out.println(body);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
改进解决方法:
@Override
public void startServer(int port) throws IOException {
ServerSocket serverSocket = new ServerSocket(port);
AtomicInteger num = new AtomicInteger(0);
Executor executor = Executors.newFixedThreadPool(6);
while (true) {
Socket cli = serverSocket.accept();
// new Thread(() -> {
// new Server(port, cli, num.incrementAndGet()).start();
// }).start();
executor.execute(() -> {
new Server(port,cli,num.incrementAndGet()).start();
});
}
}