DefaultChannelGroup 是getty内部提供用于保存通道的一个group类,用于保存通道对象以备方便使用。

    示例:

    1. public class SimpleHandler extends SimpleChannelInboundHandler<MessageClass.Message> {
    2. //实例化一个group保存客户端连接
    3. DefaultChannelGroup defaultChannelGroup = new DefaultChannelGroup();
    4. @Override
    5. public void channelAdded(AioChannel aioChannel) {
    6. System.out.println("连接过来了");
    7. //把连接保存起来以备使用
    8. defaultChannelGroup.add(aioChannel);
    9. //可以通过AioChannel的channelId获取通道。比如与用户映射起来
    10. AioChannel tempChannel = defaultChannelGroup.find(aioChannel.getChannelId());
    11. tempChannel.writeAndFlush("123".getBytes());
    12. }
    13. @Override
    14. public void channelClosed(AioChannel aioChannel) {
    15. System.out.println("连接关闭了");
    16. }
    17. @Override
    18. public void channelRead0(AioChannel aioChannel, MessageClass.Message str) {
    19. System.out.println("读取消息:" + str.getId());
    20. }
    21. @Override
    22. public void exceptionCaught(AioChannel aioChannel, Throwable cause, PipelineDirection pipelineDirection) {
    23. System.out.println("出错了");
    24. }
    25. }