# base-rpc **Repository Path**: iso-iec-14882-c--2077/base-rpc ## Basic Information - **Project Name**: base-rpc - **Description**: 本项目为io框架,支持aio/bio/nio 当作网络通信的基础框架,采用protobuf和json进行数据传输 - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 1 - **Created**: 2023-01-13 - **Last Updated**: 2024-11-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: NIO, aio, Java, protubuf ## README # base-rpc #### 介绍 本项目为io框架,支持aio/bio/nio 当作网络通信的基础框架,采用protobuf和json进行数据传输 #### 快速入门 ##### nio(主从分离reactor) ###### 服务端 ###### 解码器 ```java public static class StringIOBaseProtocol implements IOBaseProtocol { private final Map decoderMap = new ConcurrentHashMap<>(); @Override public String decode(TCPSession tcpSession, ByteBuffer readBuffer) { int remaining = readBuffer.remaining(); if (remaining < Integer.BYTES) { return null; } readBuffer.mark(); int length = readBuffer.getInt(); //消息长度超过缓冲区容量引发的半包,启用定长消息解码器,本次解码失败 if (length + Integer.BYTES > readBuffer.capacity()) { FixedLengthFrameDecoder fixedLengthFrameDecoder = new FixedLengthFrameDecoder(length); decoderMap.put(tcpSession, fixedLengthFrameDecoder); return null; } //半包,解码失败 if (length > readBuffer.remaining()) { readBuffer.reset(); return null; } return convert(readBuffer, length); } /** * 消息解码 */ private String convert(ByteBuffer byteBuffer, int length) { byte[] b = new byte[length]; byteBuffer.get(b); return new String(b, StandardCharsets.UTF_8); } } ``` ###### 通道处理器 ```java public static class StringProcessor implements TCPProcessor { @Override public void process(TCPSession session, String msg) { System.out.printf(msg); if (msg.equals("你好2")) { byte[] bytes = "收到".getBytes(); ByteBuffer buffer = ByteBuffer.allocate(Config.WRITE_BUFFER_SIZE); buffer.putInt(bytes.length); buffer.put(bytes); buffer.flip(); session.setWriteBuffer(buffer); } } } ``` ###### 启动服务端 ```java public static void main(String[] args) throws IOException { ReactorSocketServer reactorSocketServer = new ReactorSocketServer("127.0.0.1", 7777, new StringIOBaseProtocol(), new StringProcessor()); reactorSocketServer.start(); } ``` ###### 客户端 ```java public static void main(String[] args) throws Exception { //启动我们客户端 ReactorClient chatClient = new ReactorClient("127.0.0.1", 7777, new StringIOBaseProtocol(), new StringProcessor()); chatClient.start(); chatClient.send("你好1".getBytes()); chatClient.send("你好2".getBytes()); chatClient.send("你好3".getBytes()); chatClient.send("你好4".getBytes()); Thread.sleep(1000); chatClient.stop(); } ``` ###### 如下实例 ![img.png](img.png) ![img_1.png](img_1.png) #### AIO #### IO