Netty-聊天室

1. 实例要求
  1. 编写一个 Netty 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
  2. 实现多人群聊
  3. 服务器端:可以监测用户上线,离线,并实现消息转发功能
  4. 客户端:通过 channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发 得到)
  5. 目的:进一步理解 Netty 非阻塞网络编程机制
2. 代码

GroupChatServer.java

public class GroupChatServer {
    // 监听端口
    private int port;

    public GroupChatServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 加入编码-解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());

                            // 加入自己的handler
                            pipeline.addLast(new GroupChatServerHandler());
                        }
                    });

            System.out.println("GroupChatServer is ready...\n");
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        try {
            new GroupChatServer(5758).run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

GroupChatServerHandler.java

public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
    /**
     * 定义一个 Channel 组,管理所有的 Channel
     * GlobalEventExecutor.INSTANCE 全局执行器
     */
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 日期格式
     */
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * Channel连接完毕 处于活动状态 触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 服务端提示 xxx客户端上线了
        System.out.println(String.format("[客户端%s]上线了~ %s\n", ctx.channel().remoteAddress(), sdf.format(new Date())));
    }

    /**
     * Channel断开完毕 非活动状态 触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 服务端提示 xxx客户端离线
        System.out.println(String.format("[客户端%s]离线了~ %s\n", ctx.channel().remoteAddress(), sdf.format(new Date())));
    }

    /**
     * Channel连接建立 触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        // 向其他Channel广播 该Channel已连接的消息
        String msg = String.format("[客户端%s]加入聊天 %s\n", channel.remoteAddress(), sdf.format(new Date()));
        channelGroup.writeAndFlush(msg);

        // 把该Channel加入到Channel组中
        channelGroup.add(channel);
    }

    /**
     * Channel断开连接 触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 将该Channel离线消息广播给其他Channel
        // Channel断开会自动从ChannelGroup中移除,无需手动移除
        Channel channel = ctx.channel();
        String msg = String.format("[客户端%s]离开了 %s\n", channel.remoteAddress(), sdf.format(new Date()));
        channelGroup.writeAndFlush(msg);
    }

    /**
     * 读事件 触发
     * @param ctx 上下文
     * @param msg 客户端发来的数据
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 将该Channel消息广播给其他Channel
        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> {
            if (channel == ch) {
                ch.writeAndFlush(String.format("[自己%s %s]: %s\n", channel.remoteAddress(), sdf.format(new Date()), msg));
            } else {
                ch.writeAndFlush(String.format("[客户端%s %s]: %s\n", channel.remoteAddress(), sdf.format(new Date()), msg));
            }
        });
    }

    /**
     * 捕获异常
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        if (channel.isActive()) {
            cause.printStackTrace();
        } else {
            channel.close();
            System.out.println(String.format("[客户端%s]离线~\n", channel.localAddress()));
        }
    }
}

GroupChatClient

public class GroupChatClient {
    // 主机与端口
    private final String host;
    private final int port;

    public GroupChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //添加 编码-解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            // 加入自定义handler
                            pipeline.addLast(new SimpleChannelInboundHandler<String>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                    // 显示服务端发送的消息
                                    System.out.println(msg.trim());
                                }
                            });
                        }
                    });

            // 连接服务器
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();

            // 创建客户端个输入扫描器
            Channel channel = channelFuture.channel();
            System.out.println(String.format("------%s------\n", channel.localAddress()));
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                // 发送到服务器
                channel.writeAndFlush(scanner.nextLine());
            }
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        try {
            new GroupChatClient("127.0.0.1", 5758).run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
3 运行结果

server
在这里插入图片描述
client1
在这里插入图片描述
client2
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值