在 Netty 中,通常使用 Channel 的 write() 方法来主动向客户端发送消息。
例如,你可以在服务端的 ChannelHandler 中实现 channelRead() 方法,在收到客户端的消息后主动向客户端发送响应消息:
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 将客户端发送的消息转换为字符串
String request = (String) msg;
System.out.println("Server received: " + request);
// 在这里主动向客户端发送消息
String response = "Hello, " + request + "!";
ctx.write(response);
}
需要注意的是,Netty 使用了异步的消息处理机制,所以在调用 write() 方法后,消息并不会立即发送出去,而是会缓存在发送缓冲区中。为了将缓存在发送缓冲区中的消息立即发送出去,需要调用 Channel 的 flush() 方法。
例如:
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 将客户端发送的消息转换为字符串
String request = (String) msg;
System.out.println("Server received: " + request);
// 在这里主动向客户端发送消息
String response = "Hello, " + request + "!";
ctx.write(response);
// 将发送缓冲区中的消息立即发送出去
ctx.flush();
}
在这种情况下,客户端收到的消息就是服务端主动发送的响应消息。
希望这对你