标签:并发 bio dex port 逻辑 asc 框架 play 自动
使用netty的开源框架
Dubbo:阿里开源的高性能rpc通讯框架
RocketMQ:阿里出品的高性能消息队列
Spark:为大规模数据处理设计的一款计算引擎
Elasticsearch,Cassandra,Flink,Netty-SocketIO,Spring5,Play,Grpc...
Netty是什么
Netty基本组件
在没有netty的情况下,客户端和服务端的通信
public class ServerBoot { private static final int PORT = 8000; public static void main(String[] args) {
// 启动一个server Server server = new Server(PORT); server.start(); } }
Server端的代码如下:
public class Server { private ServerSocket serverSocket; public Server(int port) { try {
// 根据端口号绑定端口 this.serverSocket = new ServerSocket(port); System.out.println("服务端启动成功,端口:" + port); } catch (IOException exception) { System.out.println("服务端启动失败"); } }
// 避免创建server的程序阻塞ServerBoot的主线程,所以把端口监听放到一个独立的线程中 public void start() { new Thread(new Runnable() { @Override public void run() { doStart(); } }).start(); }
// 接收客户端的连接 private void doStart() { while (true) { try {
// 接收到客户端连接,accept是个阻塞方法,当一个客户端过来后才创建socket Socket client = serverSocket.accept();
// 避免socket读写阻塞serverSocket.accept,所以ClientHandler需要新建一个线程 new ClientHandler(client).start(); } catch (IOException e) { System.out.println("服务端异常"); } } } }
ClientHandler代码如下:
public class ClientHandler { public static final int MAX_DATA_LEN = 1024;
// 保存客户端socket private final Socket socket; public ClientHandler(Socket socket) { this.socket = socket; } public void start() { System.out.println("新客户端接入"); new Thread(new Runnable() { @Override public void run() { doStart(); } }).start(); } private void doStart() { try { InputStream inputStream = socket.getInputStream();
// 客户端与服务端通信 while (true) { byte[] data = new byte[MAX_DATA_LEN]; int len; while ((len = inputStream.read(data)) != -1) { String message = new String(data, 0, len); System.out.println("客户端传来消息: " + message); socket.getOutputStream().write(data); } } } catch (IOException e) { e.printStackTrace(); } } }
客户端Client的代码如下:
public class Client { private static final String HOST = "127.0.0.1"; private static final int PORT = 9010; private static final int SLEEP_TIME = 5000; public static void main(String[] args) throws IOException { final Socket socket = new Socket(HOST, PORT); new Thread(new Runnable() { @Override public void run() { System.out.println("客户端启动成功!"); while (true) { try { String message = "hello world"; System.out.println("客户端发送数据: " + message); socket.getOutputStream().write(message.getBytes()); } catch (Exception e) { System.out.println("写数据出错!"); } sleep(); } } }).start(); } private static void sleep() { try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } }
客户端与服务端通信的逻辑:
服务端视角:
以上过程跟netty组件对应起来的关系如下:
标签:并发 bio dex port 逻辑 asc 框架 play 自动
原文地址:https://www.cnblogs.com/liekkas01/p/12639989.html