Netty入门实战——TCP服务、群聊系统的实现

TCP 服务

Netty 服务器在 6667 端口监听,客户端上线后发送消息给服务器,服务器接收并回复消息给客户端。总的来说就是一来一回。

NettyServer 服务器启动类

public class NettyServer {

    private static final int PORT = 6667;

    public static void main(String[] args) {
        //1.创建两个线程组 BossGroup、WorkerGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup(1); //只处理连接请求
        EventLoopGroup workerGroup = new NioEventLoopGroup(); //处理与客户端的IO传输以及业务处理
        try {
            //2.创建服务器启动类
            ServerBootstrap bootstrap = new ServerBootstrap();
            //3.为服务器启动类并绑定Channel、父子线程组
            bootstrap.group(bossGroup, workerGroup) //设置父子线程组
                    .channel(NioServerSocketChannel.class) //设置channel:客户端与服务端通信的nio双向通道
                    .option(ChannelOption.SO_BACKLOG, 128) //设置连接队列的长度(半连接队列+全连接队列之和)
                    .childOption(ChannelOption.SO_KEEPALIVE, true) //设置保持活动连接状态
                    //4.给子线程组的pipeline流水线设置处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            //5.绑定端口号,启动服务器(同步方式)
            ChannelFuture channelFuture = bootstrap.bind(PORT).sync();
            //监听通道关闭
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6.优雅关闭 EventLoopGroup
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

NettyServerHandler 自定义服务器Handler

public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读取数据
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("收到客户端" + channel.remoteAddress() + "发送的数据是:" + byteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 读取数据完毕后的处理
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将数据写入到缓存,并刷新
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端", CharsetUtil.UTF_8));
    }

    /**
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

NettyClient 客户端启动类

public class NettyClient {

    public static void main(String[] args) {
        //创建一个事件循环组
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            //创建客户端启动类
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            //启动客户端连接服务器
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6667).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}

NettyClientHandler 自定义客户端Handler

public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 当通道就绪会触发该方法
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello server", CharsetUtil.UTF_8));
    }

    /**
     * 当通道有读取事件时触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("服务端" + ctx.channel().remoteAddress() +
                "发来消息:" + byteBuf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}


群聊系统

编写一个 Netty 群聊系统,实现服务器端和客户端之间的非阻塞通讯,实现多人群聊。

  • 服务器端可以监测用户上线,离线,以及实现消息转发功能,并添加心跳检测机制。
  • 客户端可以通过 channel 无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(由服务器转发得到)。

GroupChatServer 服务端启动类

public class GroupChatServer {

    private static final int PORT = 6667;

    public void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO)) //日志处理器
                    .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());
                            //添加心跳检测处理器
                            pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
                            pipeline.addLast(new GroupChatServerHandler());
                        }
                    });
            System.out.println("netty服务端启动...");
            ChannelFuture channelFuture = serverBootstrap.bind(PORT).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new GroupChatServer().run();
    }
}

GroupChatServerHandler 服务端自定义Handler

public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //心跳检测:空闲事件触发
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String eventType = null;
            switch (event.state()) {
                case READER_IDLE:
                    eventType = "读空闲";
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
                case ALL_IDLE:
                    eventType = "读写空闲";
                    break;
            }
            System.out.println(ctx.channel().remoteAddress() + eventType);
            ctx.channel().close(); //如果发生空闲,则关闭通道(根据业务决定)
        }
    }

    /**
     * 连接建立时第一个执行
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //将客户端加入群聊的消息推送给其他在线的客户端
        channelGroup.writeAndFlush("[客户端] " + channel.remoteAddress() + " 加入聊天 —— " + sdf.format(new Date()));
        channelGroup.add(channel);
    }

    /**
     * 断开连接,并推送给其他客户端
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端] " + channel.remoteAddress() + " 离开了");
        //自动remove
    }

    /**
     * 表示channel处于活动状态
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 上线了~");
    }

    /**
     * 表示channel处于不活动状态
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 离线了~");
    }

    /**
     * 读取数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> {
            if (ch != channel) {
                ch.writeAndFlush("[客户端] " + channel.remoteAddress() + " 发送了消息: " + msg);
            } else {
                ch.writeAndFlush("自己发送了: " + msg);
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

GroupChatClient 客户端启动类

public class GroupChatClient {

    private static final String HOST = "127.0.0.1";
    private static final int PORT = 6667;

    public void run() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .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());
                            pipeline.addLast(new GroupChatClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync();
            Channel channel = channelFuture.channel();
            System.out.println("------" + channel.remoteAddress() + "------");
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String readLine;
            while ((readLine = reader.readLine()) != null) {
                channel.writeAndFlush(readLine);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new GroupChatClient().run();
    }
}

GroupChatClientHandler 客户端自定义Handler

public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg.trim());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Netty入门实战: 仿写微信IM即时通讯系统》是一本关于网络编程框架Netty的实践指南。本书以仿写微信IM即时通讯系统为例,通过实际的项目案例引导读者学习和掌握Netty的使用。 Netty是一款基于Java的网络编程框架,提供了高性能、异步、事件驱动的特性。在本书中,作者基于Netty框架,通过分析微信IM即时通讯系统的架构和功能需求,逐步引入Netty的概念和使用方法。 首先,本书介绍了Netty的基本概念和工作原理,解释了Netty的事件驱动模型以及异步IO操作的优势。接着,读者会学习到如何使用Netty构建网络服务器和客户端,以及如何处理网络通信中的数据包、编解码、心跳检测等问题。同时,本书也强调了Netty在高并发情况下的性能优势,示范了如何使用Netty进行性能优化和扩展。 通过跟随本书的实例代码,读者将逐步了解和掌握Netty的各项功能和使用方法。同时,通过仿写微信IM即时通讯系统的实践项目,读者也能够更好地理解Netty框架在实际项目中的应用场景和解决方案。 总而言之,《Netty入门实战: 仿写微信IM即时通讯系统》通过实际案例的方式,帮助读者深入理解Netty框架的使用和原理,并将其应用于实际的项目中。无论是对于新手还是有一定经验的开发者来说,本书都是一个很好的学习和实践指南,能够帮助读者快速入门和提升自己在网络编程领域的技能水平。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值