在简单聊天室的代码中修改ChatServerHandler类,就可以模拟多人聊天的功能
1package com.cppdy.server; 2 3import io.netty.channel.Channel; 4import io.netty.channel.ChannelHandlerContext; 5import io.netty.channel.SimpleChannelInboundHandler; 6import io.netty.channel.group.ChannelGroup; 7import io.netty.channel.group.DefaultChannelGroup; 8import io.netty.util.concurrent.GlobalEventExecutor; 9 10public class ChatServerHandler extends SimpleChannelInboundHandler<String> { 11 12 // 存放channel的集合 13 public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); 14 15 @Override 16 protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 17 18 System.out.println(msg); 19 20 for (Channel channel : channels) { 21 if (!channel.equals(ctx.channel())) { 22 channel.writeAndFlush("[Server]-" + "[" + channel.remoteAddress() + "]" + msg); 23 } 24 } 25 26 } 27 28 @Override 29 public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 30 System.out.println(ctx.channel().remoteAddress()+"--连接上了"); 31 channels.add(ctx.channel()); 32 } 33 34 @Override 35 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { 36 System.out.println(ctx.channel().remoteAddress()+"--退出了"); 37 channels.remove(ctx.channel()); 38 } 39 40 @Override 41 public void channelActive(ChannelHandlerContext ctx) throws Exception { 42 System.out.println(ctx.channel().remoteAddress()+"--上线了"); 43 } 44 45 @Override 46 public void channelInactive(ChannelHandlerContext ctx) throws Exception { 47 System.out.println(ctx.channel().remoteAddress()+"--掉线了"); 48 } 49 50 @Override 51 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 52 System.out.println(ctx.channel().remoteAddress()+"--error"); 53 } 54 55}
先启动ChatServer类,再启动2次ChatClient类,就可以模拟两个客户端互发消息的功能。