简体   繁体   English

Netty:从管道外部向所有(TCP)客户端发送消息

[英]Netty: send messages to all (TCP) clients from outside the pipeline

I'm migrating my "plain NIO" (= I used the packages from the JDK directly) TCP server to Netty 4. 我正在将我的“普通NIO”(=我直接从JDK使用这些包)TCP服务器迁移到Netty 4。

I have threads that send messages to all clients, like health-checking packets, chat message broadcasts, direct chat messages to a single client, ... using a Collection of SocketChannels that I keep somewhere. 我有线程将消息发送到所有客户端,例如运行状况检查数据包,聊天消息广播,将聊天消息定向到单个客户端,...使用我保存在某个地方的SocketChannels集合。

How do I do that in Netty? 如何在Netty中做到这一点? Would it be wise to simply share a ChannelGroup between one of the Netty handlers and the threads that need to send messages? 在Netty处理程序之一和需要发送消息的线程之间共享一个ChannelGroup是否明智? The channel would look like this: 该通道如下所示:

public class ChannelCollectorHandler extends ChannelInboundMessageHandlerAdapter<String> {

    private static final ChannelGroup channels = new DefaultChannelGroup();

    public SecureChatServerHandler(ChannelGroup channels) {
       this.channels = channels;
    }


    @Override
    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
        channels.add(ctx.channel());
    }

    ...
}

in all the threads I would then simply do: 在所有线程中,我只需执行以下操作:

channels.write(...);

will that work? 那行得通吗?

Yes this will work without problems. 是的,这将毫无问题地起作用。 ChannelGroup was designed for tasks like this. ChannelGroup专为执行此类任务而设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM