企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
服务端 ~~~ import java.io.*; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; public class Server { public static void main(String[] args) throws IOException { // 服务端通道 final ServerSocketChannel ssChannel = ServerSocketChannel.open(); // 配置阻塞为false ssChannel.configureBlocking(false); // 绑定端口 ssChannel.bind(new InetSocketAddress(9999)); final Selector selector = Selector.open(); // 将通道都注册到选择器上,并且开始监听事件 ssChannel.register(selector, SelectionKey.OP_ACCEPT); // 使用Selector选择器已经准备好的事件 while (selector.select()>0){ // 获取选择器中所有注册的通道已经就绪好的事件 final Iterator<SelectionKey> iterator = selector .selectedKeys() .iterator(); while (iterator.hasNext()){ final SelectionKey selectionKey = iterator.next(); if (selectionKey.isAcceptable()){ final SocketChannel accept = ssChannel.accept(); accept.configureBlocking(false); // 读 accept.register(selector,SelectionKey.OP_READ); } // 读 if (selectionKey.isReadable()){ final SocketChannel channel =(SocketChannel) selectionKey.channel(); final ByteBuffer allocate = ByteBuffer.allocate(1024); int len=0; while ((len=channel.read(allocate))>0){ allocate.flip(); System.out.println(new String(allocate.array(),0,len)); allocate.clear(); } } iterator.remove(); } } } } ~~~ 客户端 ~~~ import java.io.*; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.Scanner; public class Client { public static void main(String[] args) throws IOException { final SocketChannel open = SocketChannel.open(new InetSocketAddress(9999)); open.configureBlocking(false); final ByteBuffer allocate = ByteBuffer.allocate(1024); final Scanner scanner = new Scanner(System.in); while (true){ System.out.println("请说话:"); final String line = scanner.nextLine(); allocate.put(line.getBytes()); allocate.flip(); open.write(allocate); allocate.clear(); } } } ~~~