AIO封装-AioServer和AioClient

由来

在JDK7+后,提供了异步Socket库——AIO,Hutool对其进行了简单的封装。

使用

服务端

  1. AioServer aioServer = new AioServer(8899);
  2. aioServer.setIoAction(new SimpleIoAction() {
  3. @Override
  4. public void accept(AioSession session) {
  5. StaticLog.debug("【客户端】:{} 连接。", session.getRemoteAddress());
  6. session.write(BufferUtil.createUtf8("=== Welcome to Hutool socket server. ==="));
  7. }
  8. @Override
  9. public void doAction(AioSession session, ByteBuffer data) {
  10. Console.log(data);
  11. if(false == data.hasRemaining()) {
  12. StringBuilder response = StrUtil.builder()//
  13. .append("HTTP/1.1 200 OK\r\n")//
  14. .append("Date: ").append(DateUtil.formatHttpDate(DateUtil.date())).append("\r\n")//
  15. .append("Content-Type: text/html; charset=UTF-8\r\n")//
  16. .append("\r\n")
  17. .append("Hello Hutool socket");//
  18. session.writeAndClose(BufferUtil.createUtf8(response));
  19. }else {
  20. session.read();
  21. }
  22. }
  23. }).start(true);

客户端

  1. AioClient client = new AioClient(new InetSocketAddress("localhost", 8899), new SimpleIoAction() {
  2. @Override
  3. public void doAction(AioSession session, ByteBuffer data) {
  4. if(data.hasRemaining()) {
  5. Console.log(StrUtil.utf8Str(data));
  6. session.read();
  7. }
  8. Console.log("OK");
  9. }
  10. });
  11. client.write(ByteBuffer.wrap("Hello".getBytes()));
  12. client.read();
  13. client.close();