1.server端:

    1. import io.netty.bootstrap.ServerBootstrap;
    2. import io.netty.channel.*;
    3. import io.netty.channel.nio.NioEventLoopGroup;
    4. import io.netty.channel.socket.SocketChannel;
    5. import io.netty.channel.socket.nio.NioServerSocketChannel;
    6. import io.netty.handler.codec.string.StringDecoder;
    7. import io.netty.handler.codec.string.StringEncoder;
    8. public class ChatServer {
    9. public static void main(String[] args) throws Exception {
    10. EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    11. EventLoopGroup workerGroup = new NioEventLoopGroup(8);
    12. try {
    13. ServerBootstrap bootstrap = new ServerBootstrap();
    14. bootstrap.group(bossGroup, workerGroup)
    15. .channel(NioServerSocketChannel.class)
    16. .option(ChannelOption.SO_BACKLOG, 1024)
    17. .childHandler(new ChannelInitializer<SocketChannel>() {
    18. @Override
    19. protected void initChannel(SocketChannel ch) throws Exception {
    20. ChannelPipeline pipeline = ch.pipeline();
    21. //加入特殊分隔符分包解码器
    22. //pipeline.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("_"
    23. // .getBytes())));
    24. //向pipeline加入解码器
    25. pipeline.addLast("decoder", new StringDecoder());
    26. //向pipeline加入编码器
    27. pipeline.addLast("encoder", new StringEncoder());
    28. //加入自己的业务处理handler
    29. pipeline.addLast(new ChatServerHandler());
    30. }
    31. });
    32. System.out.println("聊天室server启动。。");
    33. ChannelFuture channelFuture = bootstrap.bind(9000).sync();
    34. //关闭通道
    35. channelFuture.channel().closeFuture().sync();
    36. } finally {
    37. bossGroup.shutdownGracefully();
    38. workerGroup.shutdownGracefully();
    39. }
    40. }
    41. }
    1. import io.netty.channel.Channel;
    2. import io.netty.channel.ChannelHandlerContext;
    3. import io.netty.channel.SimpleChannelInboundHandler;
    4. import io.netty.channel.group.ChannelGroup;
    5. import io.netty.channel.group.DefaultChannelGroup;
    6. import io.netty.util.concurrent.GlobalEventExecutor;
    7. import java.text.SimpleDateFormat;
    8. public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
    9. //GlobalEventExecutor.INSTANCE 是全局的事件执行器,是一个单例
    10. private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    11. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    12. //表示 channel 处于就绪状态, 提示上线
    13. @Override
    14. public void channelActive(ChannelHandlerContext ctx) {
    15. Channel channel = ctx.channel();
    16. //将该客户加入聊天的信息推送给其它在线的客户端
    17. //该方法会将 channelGroup 中所有的 channel 遍历,并发送消息
    18. channelGroup.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + " 上线了 " + sdf.format(new
    19. java.util.Date()) + "\n");
    20. //将当前 channel 加入到 channelGroup
    21. channelGroup.add(channel);
    22. System.out.println(ctx.channel().remoteAddress() + " 上线了" + "\n");
    23. }
    24. //表示 channel 处于不活动状态, 提示离线了
    25. @Override
    26. public void channelInactive(ChannelHandlerContext ctx) {
    27. Channel channel = ctx.channel();
    28. //将客户离开信息推送给当前在线的客户
    29. channelGroup.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + " 下线了" + "\n");
    30. System.out.println(ctx.channel().remoteAddress() + " 下线了" + "\n");
    31. System.out.println("channelGroup size=" + channelGroup.size());
    32. }
    33. //读取数据
    34. @Override
    35. protected void channelRead0(ChannelHandlerContext ctx, String msg) {
    36. //获取到当前 channel
    37. Channel channel = ctx.channel();
    38. //这时我们遍历 channelGroup, 根据不同的情况, 回送不同的消息
    39. channelGroup.forEach(ch -> {
    40. if (channel != ch) { //不是当前的 channel,转发消息
    41. ch.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + " 发送了消息:" + msg + "\n");
    42. } else {//回显自己发送的消息给自己
    43. ch.writeAndFlush("[ 自己 ]发送了消息:" + msg + "\n");
    44. }
    45. });
    46. }
    47. @Override
    48. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    49. //关闭通道
    50. ctx.close();
    51. }
    52. }

    2.客户端

    1. import io.netty.bootstrap.Bootstrap;
    2. import io.netty.channel.*;
    3. import io.netty.channel.nio.NioEventLoopGroup;
    4. import io.netty.channel.socket.SocketChannel;
    5. import io.netty.channel.socket.nio.NioSocketChannel;
    6. import io.netty.handler.codec.string.StringDecoder;
    7. import io.netty.handler.codec.string.StringEncoder;
    8. import java.util.Scanner;
    9. public class ChatClient {
    10. public static void main(String[] args) throws Exception {
    11. EventLoopGroup group = new NioEventLoopGroup();
    12. try {
    13. Bootstrap bootstrap = new Bootstrap();
    14. bootstrap.group(group)
    15. .channel(NioSocketChannel.class)
    16. .handler(new ChannelInitializer<SocketChannel>() {
    17. @Override
    18. protected void initChannel(SocketChannel ch) throws Exception {
    19. ChannelPipeline pipeline = ch.pipeline();
    20. //pipeline.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("_"
    21. // .getBytes())));
    22. //向pipeline加入解码器
    23. pipeline.addLast("decoder", new StringDecoder());
    24. //向pipeline加入编码器
    25. pipeline.addLast("encoder", new StringEncoder());
    26. //加入自己的业务处理handler
    27. pipeline.addLast(new ChatClientHandler());
    28. }
    29. });
    30. ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9000).sync();
    31. //得到 channel
    32. Channel channel = channelFuture.channel();
    33. System.out.println("========" + channel.localAddress() + "========");
    34. //客户端需要输入信息, 创建一个扫描器
    35. Scanner scanner = new Scanner(System.in);
    36. while (scanner.hasNextLine()) {
    37. String msg = scanner.nextLine();
    38. //通过 channel 发送到服务器端
    39. channel.writeAndFlush(msg);
    40. }
    41. /*for (int i = 0; i < 200; i++) {
    42. channel.writeAndFlush("hello,诸葛!" + "_");
    43. }*/
    44. } finally {
    45. group.shutdownGracefully();
    46. }
    47. }
    48. }
    1. import io.netty.channel.ChannelHandlerContext;
    2. import io.netty.channel.SimpleChannelInboundHandler;
    3. public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
    4. @Override
    5. protected void channelRead0(ChannelHandlerContext ctx, String msg){
    6. System.out.println(msg.trim());
    7. }
    8. }