packagetest;importcn.hutool.core.io.BufferUtil;importcn.hutool.core.io.IORuntimeException;importcn.hutool.core.io.IoUtil;importcn.hutool.core.lang.Console;importcn.hutool.core.util.StrUtil;importcn.hutool.socket.nio.NioServer;importcom.alibaba.fastjson.JSONArray;importjava.io.IOException;importjava.nio.ByteBuffer;importjava.nio.channels.SocketChannel;publicclassServerTest{publicstaticvoidmain(String[] args){NioServer server =newNioServer(8080);
server.setChannelHandler((sc)->{ByteBuffer readBuffer =ByteBuffer.allocate(1024);try{//从channel读数据到缓冲区int readBytes = sc.read(readBuffer);if(readBytes >0){//Flips this buffer. The limit is set to the current position and then// the position is set to zero,就是表示要从起始位置开始读取数据
readBuffer.flip();//eturns the number of elements between the current position and the limit.// 要读取的字节长度byte[] bytes =newbyte[readBuffer.remaining()];//将缓冲区的数据读到bytes数组
readBuffer.get(bytes);String body =StrUtil.utf8Str(bytes);Console.log("[{}]: {}", sc.getRemoteAddress(), body);doWrite(sc, body);}elseif(readBytes <0){IoUtil.close(sc);}}catch(IOException e){thrownewIORuntimeException(e);}});
server.listen();}publicstaticvoiddoWrite(SocketChannel channel,String response)throwsIOException{
response ="收到消息:"+ response;//将缓冲数据写入渠道,返回给客户端
channel.write(BufferUtil.createUtf8(response));}}