public interface ChannelGroup extends Set<Channel>, Comparable<ChannelGroup>
A thread-safe
Set
that contains open
Channel
s and provides various bulk operations on them. Using
ChannelGroup
,
一个线程安全的Set容器提供对Channels的操作
you can categorize
Channel
s 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 Channel
s
广播一条消息到多个Channel
If you need to broadcast a message to more than one Channel
, you can add the Channel
s associated with the recipients
如果你需要广播一条消息到多个Channel,你可以添加Channels
and call write(Object)
:
ChannelGroup
recipients = newDefaultChannelGroup
(); 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 ServerChannel
s and non-ServerChannel
s exist in the same ChannelGroup
, any requested I/O operations on the group are performed for the ServerChannel
s first and then for the others.
This rule is very useful when you shut down a server in one shot:
ChannelGroup
allChannels = newDefaultChannelGroup
(); public static void main(String[] args) throws Exception {ServerBootstrap
b = newServerBootstrap
(..); ... // 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 extendsSimpleChannelUpstreamHandler
{@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()); } }