ChannelGroup

public interface ChannelGroup
extends Set<Channel>, Comparable<ChannelGroup>
A thread-safe  Set that contains open  Channels and provides various bulk operations on them. Using  ChannelGroup,
一个线程安全的Set容器提供对Channels的操作
you can categorize  Channels into a meaningful group (e.g. on a per-service or per-state basis.) A closed  Channel is
你可以把Channels归类为一个有意义的组,Channel的closed关闭会自动的从集合中移除整个Channel,
automatically removed from the collection, so that you don't need to worry about the life cycle of the added  Channel. A  Channel can belong to more than one  ChannelGroup.
因此你不必担心一个Channel会同时属于不同的ChannelGroup

Broadcast a message to multiple Channels

广播一条消息到多个Channel

 

If you need to broadcast a message to more than one Channel, you can add the Channels associated with the recipients

如果你需要广播一条消息到多个Channel,你可以添加Channels 

and call write(Object):

 ChannelGroup recipients = new DefaultChannelGroup();
 recipients.add(channelA);
 recipients.add(channelB);
 ..
 recipients.write(ChannelBuffers.copiedBuffer(
         "Service will shut down for maintenance in 5 minutes.",
         CharsetUtil.UTF_8));
 

Simplify shutdown process with ChannelGroup

If both ServerChannels and non-ServerChannels exist in the same ChannelGroup, any requested I/O operations on the group are performed for the ServerChannels first and then for the others.

This rule is very useful when you shut down a server in one shot:

 ChannelGroup allChannels = new DefaultChannelGroup();

 public static void main(String[] args) throws Exception {
     ServerBootstrap b = new ServerBootstrap(..);
     ...

     // Start the server
     b.getPipeline().addLast("handler", new MyHandler());
     Channel serverChannel = b.bind(..);
     allChannels.add(serverChannel);

     ... Wait until the shutdown signal reception ...

     // Close the serverChannel and then all accepted connections.
     allChannels.close().awaitUninterruptibly();
     b.releaseExternalResources();
 }

 public class MyHandler extends SimpleChannelUpstreamHandler {
     @Override
     public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
         // Add all open channels to the global group so that they are
         // closed on shutdown.
         allChannels.add(e.getChannel());
     }
 }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值