在服务器端,如果需要类似群聊的模块时,可以在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);
}