NIO封装-NioServer和NioClient

由来

Hutool对NIO其进行了简单的封装。

使用

服务端

  1. NioServer server = new NioServer(8080);
  2. server.setChannelHandler((sc)->{
  3. ByteBuffer readBuffer = ByteBuffer.allocate(1024);
  4. try{
  5. //从channel读数据到缓冲区
  6. int readBytes = sc.read(readBuffer);
  7. if (readBytes > 0) {
  8. //Flips this buffer. The limit is set to the current position and then
  9. // the position is set to zero,就是表示要从起始位置开始读取数据
  10. readBuffer.flip();
  11. //eturns the number of elements between the current position and the limit.
  12. // 要读取的字节长度
  13. byte[] bytes = new byte[readBuffer.remaining()];
  14. //将缓冲区的数据读到bytes数组
  15. readBuffer.get(bytes);
  16. String body = StrUtil.utf8Str(bytes);
  17. Console.log("[{}]: {}", sc.getRemoteAddress(), body);
  18. doWrite(sc, body);
  19. } else if (readBytes < 0) {
  20. IoUtil.close(sc);
  21. }
  22. } catch (IOException e){
  23. throw new IORuntimeException(e);
  24. }
  25. });
  26. server.listen();
  1. public static void doWrite(SocketChannel channel, String response) throws IOException {
  2. response = "收到消息:" + response;
  3. //将缓冲数据写入渠道,返回给客户端
  4. channel.write(BufferUtil.createUtf8(response));
  5. }

客户端

  1. NioClient client = new NioClient("127.0.0.1", 8080);
  2. client.setChannelHandler((sc)->{
  3. ByteBuffer readBuffer = ByteBuffer.allocate(1024);
  4. //从channel读数据到缓冲区
  5. int readBytes = sc.read(readBuffer);
  6. if (readBytes > 0) {
  7. //Flips this buffer. The limit is set to the current position and then
  8. // the position is set to zero,就是表示要从起始位置开始读取数据
  9. readBuffer.flip();
  10. //returns the number of elements between the current position and the limit.
  11. // 要读取的字节长度
  12. byte[] bytes = new byte[readBuffer.remaining()];
  13. //将缓冲区的数据读到bytes数组
  14. readBuffer.get(bytes);
  15. String body = StrUtil.utf8Str(bytes);
  16. Console.log("[{}]: {}", sc.getRemoteAddress(), body);
  17. } else if (readBytes < 0) {
  18. sc.close();
  19. }
  20. });
  21. client.listen();
  22. client.write(BufferUtil.createUtf8("你好。\n"));
  23. client.write(BufferUtil.createUtf8("你好2。"));
  24. // 在控制台向服务器端发送数据
  25. Console.log("请输入发送的消息:");
  26. Scanner scanner = new Scanner(System.in);
  27. while (scanner.hasNextLine()) {
  28. String request = scanner.nextLine();
  29. if (request != null && request.trim().length() > 0) {
  30. client.write(BufferUtil.createUtf8(request));
  31. }
  32. }