| public class NIOServer { |
| public static void main(String[] args) throws Exception{ |
| |
| |
| ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); |
| |
| |
| Selector selector = Selector.open(); |
| |
| |
| serverSocketChannel.socket().bind(new InetSocketAddress(6666)); |
| |
| serverSocketChannel.configureBlocking(false); |
| |
| |
| serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); |
| |
| System.out.println("注册后的selectionkey 数量=" + selector.keys().size()); |
| |
| |
| while (true) { |
| |
| if(selector.select(1000) == 0) { |
| System.out.println("服务器等待了1秒,无连接"); |
| continue; |
| } |
| |
| |
| |
| |
| |
| Set<SelectionKey> selectionKeys = selector.selectedKeys(); |
| System.out.println("selectionKeys 数量 = " + selectionKeys.size()); |
| |
| |
| Iterator<SelectionKey> keyIterator = selectionKeys.iterator(); |
| |
| while (keyIterator.hasNext()) { |
| |
| SelectionKey key = keyIterator.next(); |
| |
| if(key.isAcceptable()) { |
| |
| SocketChannel socketChannel = serverSocketChannel.accept(); |
| System.out.println("客户端连接成功 生成了一个 socketChannel " + socketChannel.hashCode()); |
| |
| socketChannel.configureBlocking(false); |
| |
| |
| socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024)); |
| |
| System.out.println("客户端连接后 ,注册的selectionkey 数量=" + selector.keys().size()); |
| } |
| if(key.isReadable()) { |
| |
| |
| SocketChannel channel = (SocketChannel)key.channel(); |
| |
| |
| ByteBuffer buffer = (ByteBuffer)key.attachment(); |
| channel.read(buffer); |
| System.out.println("form 客户端 " + new String(buffer.array())); |
| } |
| |
| |
| keyIterator.remove(); |
| } |
| } |
| } |
| } |
| public class NIOClient { |
| public static void main(String[] args) throws Exception{ |
| |
| |
| SocketChannel socketChannel = SocketChannel.open(); |
| |
| socketChannel.configureBlocking(false); |
| |
| InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666); |
| |
| if (!socketChannel.connect(inetSocketAddress)) { |
| |
| while (!socketChannel.finishConnect()) { |
| System.out.println("因为连接需要时间,客户端不会阻塞,可以做其它工作.."); |
| } |
| } |
| |
| |
| String str = "hello, 尚硅谷~"; |
| |
| ByteBuffer buffer = ByteBuffer.wrap(str.getBytes()); |
| |
| socketChannel.write(buffer); |
| System.in.read(); |
| |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决