欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

NIO 的回调调用方法

最编程 2024-10-03 14:28:31
...
package com.example.demo.callback; import java.io.IOException; 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.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.Set; public class NioServer { public static void main(String[] args) throws IOException { // 打开服务器套接字通道 ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.configureBlocking(false); serverSocket.socket().bind(new InetSocketAddress(8000)); // 打开多路复用器 Selector selector = Selector.open(); // 注册服务器通道到多路复用器上,并监听接入事件 serverSocket.register(selector, SelectionKey.OP_ACCEPT); final ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { // 非阻塞地等待注册的通道事件 selector.select(); // 获取发生事件的selectionKey集合 Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectedKeys.iterator(); // 遍历所有发生事件的selectionKey while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); // 处理接入请求 if (key.isAcceptable()) { ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = ssc.accept(); socketChannel.configureBlocking(false); SelectionKey newKey = socketChannel.register(selector, SelectionKey.OP_WRITE, ByteBuffer.allocate(1024)); //添加后可使用处理方法2处理 CommonClient client = new CommonClient(socketChannel, newKey); newKey.attach(client); } // 处理读事件 if (key.isReadable()) { SocketChannel socketChannel = (SocketChannel) key.channel(); buffer.clear(); while (socketChannel.read(buffer) > 0) { buffer.flip(); String receivedMessage = StandardCharsets.UTF_8.decode(buffer).toString(); handleReceivedMessage(socketChannel, receivedMessage); buffer.clear(); } //处理方法2 CommonClient client = (CommonClient) key.attachment(); client.onRead(); } // 处理写事件 if (key.isWritable()) { //处理方法1可以仿照方法2的格式写 //处理方法2 CommonClient client = (CommonClient) key.attachment(); client.onWrite(); } } } } // 回调函数,处理接收到的数据 private static void handleReceivedMessage(SocketChannel socketChannel, String message) throws IOException { System.out.println("Received message: " + message); // 回复客户端 socketChannel.write(ByteBuffer.wrap("Server received the message".getBytes(StandardCharsets.UTF_8))); } }