Netty 群发信息

来源:互联网 发布:shell list 添加数据 编辑:程序博客网 时间:2024/05/15 13:48

在服务器端,如果需要类似群聊的模块时,可以在handler中维护一个ChannelGroup,类似如下:

private static ChannelGroup recipients = new DefaultChannelGroup();

@Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelConnected(ctx, e);
        recipients.add(e.getChannel());
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelClosed(ctx, e);
        try {
            recipients.remove(e.getChannel());
            System.out.println("删除channel成功"+recipients.size());
        } catch (Exception ex) {
            System.out.println("删除channel失败"+ex.getMessage());
        }
    }


    @Override
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {
        if (!(e.getMessage() instanceof String)) {
            return;
        }
        String msg = (String) e.getMessage();
        System.err.println("got msg:"+msg);
             recipients.write(msg);
    }
原创粉丝点击