AioServer and AioClient

AioServer and AioClient

Origin

After JDK7+, an asynchronous Socket library, AIO, was provided, and Hutool provided a simple encapsulation of it.

Usage

Server-side

AioServer aioServer = new AioServer(8899);
aioServer.setIoAction(new SimpleIoAction() {
    
    @Override
    public void accept(AioSession session) {
        StaticLog.debug("【Client】: {} connected.", session.getRemoteAddress());
        session.write(BufferUtil.createUtf8("=== Welcome to Hutool socket server. ==="));
    }
    
    @Override
    public void doAction(AioSession session, ByteBuffer data) {
        Console.log(data);
        
        if(false == data.hasRemaining()) {
            StringBuilder response = StrUtil.builder()//
                    .append("HTTP/1.1 200 OK\r\n")//
                    .append("Date: ").append(DateUtil.formatHttpDate(DateUtil.date())).append("\r\n")//
                    .append("Content-Type: text/html; charset=UTF-8\r\n")//
                    .append("\r\n")
                    .append("Hello Hutool socket");//
            session.writeAndClose(BufferUtil.createUtf8(response));
        }else {
            session.read();
        }
    }
}).start(true);

Client-side

final AsynchronousChannelGroup GROUP = AsynchronousChannelGroup.withFixedThreadPool(//
        Runtime.getRuntime().availableProcessors(), // Default thread pool size
        ThreadFactoryBuilder.create().setNamePrefix("Huool-socket-").build()//
);

AsynchronousSocketChannel channel;
try {
    channel = AsynchronousSocketChannel.open(GROUP);
} catch (IOException e) {
    throw new IORuntimeException(e);
}
try {
    channel.connect(new InetSocketAddress("localhost", 8899)).get();
} catch (InterruptedException | ExecutionException e) {
    IoUtil.close(channel);
    throw new SocketRuntimeException(e);
}

AioClient client = new AioClient(channel, new SimpleIoAction() {
    
    @Override
    public void doAction(AioSession session, ByteBuffer data) {
        if(data.hasRemaining()) {
            Console.log(StrUtil.utf8Str(data));
            session.read();
        }
        Console.log("OK");
    }
});

client.write(ByteBuffer.wrap("Hello".getBytes()));
client.read();

client.close();

Note: GROUP maintains a connection pool and it is recommended to hold it as a global singleton.

See: https://gitee.com/dromara/hutool/issues/I56SYG