为什么要使用netty的传输方式?
这里举一个例子,例子使用经典的OIO来创建一个服务器。
public class PlainOioServer {
public void server(int port) throws IOException {
final ServerSocket socket = new ServerSocket(port);
try {
do {
final Socket clientSocket = socket.accept();
System.out.println("接受来自于" + clientSocket + "的连接");
new Thread(() -> {
OutputStream out;
try {
out = clientSocket.getOutputStream();
out.write("Hi! \r\n".getBytes(StandardCharsets.UTF_8));
out.flush();
clientSocket.close();
} catch (IOException e) {
System.out.println(ExceptionUtils.getStackTrace(e));
} finally {
try {
clientSocket.close();
} catch (IOException e) {
//ignore on close
}
}
}).start();
} while (true);
} catch (Exception e) {
System.out.println(ExceptionUtils.getStackTrace(e));
}
}
public static void main(String[] args) throws IOException {
new PlainOioServer().server(8082);
}
}
这段代码可以处理中等数量的并发客户端。但是并不能很好的伸缩到支撑成千上万的并发连接。然后决定改用异步网络编程。发现改造后的代码是这样的:
原文:https://www.cnblogs.com/StivenYang/p/14957919.html