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)));
}
}
推荐阅读
-
NIO 的回调调用方法
-
总结:无回显下的带外攻击OOB(远程代码执行)的独特方法
-
C语言必会100题(6)。利用递归方法求5!/利用递归函数调用方式,反向打印字符/五个人问岁数/输入一个不多于5位数的整数,判断是几位数/输入一个5位数,判断它是不是回文数
-
修改标题:C语言中函数的嵌套和递归函数的使用及调用方法
-
修复误删除数据的方法在dbeaver中进行回滚操作
-
深入理解JSP第四部分:EL表达式的探索与应用,包括各类数据的获取、内置对象的使用、运算功能实现、数据回显、自定义函数和fn方法库的应用
-
C语言:探索函数调用的三种方式 - 详解第二种方法
-
玩转C语言:函数的调用方法
-
多元回归分析:理解相关关系并预测结果 - 一、多元回归分析旨在研究自变量X与因变量Y之间的关联,以揭示Y形成的机制,并利用X进行预测。共有五种常见的回归分析方法,包括线性回归、0‐1回归(逻辑回归)、定序回归、计数回归和生存回归,它们的划分依据是因变量Y的不同类型。因变量还可分为连续数值型变量等多种类别。
-
C#中的委托、事件和回调函数详解