forked from haobinaa/DataStructure-DesignPattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClassicServerLoop.java
49 lines (41 loc) · 1.2 KB
/
ClassicServerLoop.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.haobin.codeBlock.IOModel;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author: HaoBin
* @create: 2019/10/23 13:52
* @description: 传统IO模型
**/
public class ClassicServerLoop implements Runnable {
private int PORT = 8080;
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (!Thread.interrupted()) {
// 这里可以换成线程池
new Thread(new Handler(serverSocket.accept())).start();
}
} catch (IOException ex) {
}
}
static class Handler implements Runnable {
final Socket socket;
Handler(Socket s) {
socket = s;
}
public void run() {
try {
byte[] input = new byte[1024];
socket.getInputStream().read(input);
byte[] output = process(input);
socket.getOutputStream().write(output);
}catch (IOException ex) {
}
}
private byte[] process(byte[] data) {
System.out.println("process data");
return "finish".getBytes();
}
}
}