我想保存传入 channel (ctx) 供以后使用,就像在 HashMap 中一样。
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8));
// example channels.put("channelname", ctx);
}
我的想法是,我可以通过字符串从 map 中获取 ctx 并从另一个类向其写入消息,如下所示:
channels.get("keyforchannel").writeAndFlush("这是我向该特定 channel 发送的消息");
有人知道我如何实现这一目标吗?
最佳答案
Netty 提供 ChannelGroup以此目的。 它不是一个映射,而是一个用于索引 Activity channel 的线程安全集。 它具有许多有用的功能,例如写入组中的所有 channel ,使用 ChannelMatcher 过滤要写入的 channel 。并在 channel 关闭时自动弹出 channel 。
关于java - netty:保存 channel 处理程序上下文以供以后使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59630980/