从入门到超神进阶的Netty群聊系统

 更新时间:2021年08月19日 15:35:56   作者:墨家巨子@俏如来  
本篇文章基于Netty做一个聊天室案例加强Netty的熟练度,案例的效果是服务端可以广播某客户端的消息给所有客户端。每个客户端监听键盘输入来获取消息,然后发送给服务端

服务端

服务端一样的需要创建BossGroup 和 WorkGroup , 然后使用ServerBootStrap 来配置Netty和启动Netty。

public class NettyGroupChatServer {
    public static void main(String[] args) {
        new NettyGroupChatServer().start();
    }
    //监听
   public void start(){
        //循环组
       NioEventLoopGroup bossGroup = new NioEventLoopGroup();
       NioEventLoopGroup workGroup = new NioEventLoopGroup();
       //启动引导
       ServerBootstrap bootstrap = new ServerBootstrap();
       //Netty配置
       bootstrap.group(bossGroup,workGroup)
               .option(ChannelOption.SO_BACKLOG,32)
               .childOption(ChannelOption.SO_KEEPALIVE,true)
               .channel(NioServerSocketChannel.class)
               .childHandler(new ChannelInitializer<SocketChannel>() {
                   @Override
                   protected void initChannel(SocketChannel channel) throws Exception {
                       //解码器
                       channel.pipeline().addLast("decoder", new StringDecoder());
                       //编码器
                       channel.pipeline().addLast("encoder",new StringEncoder());
                       //处理器
                       channel.pipeline().addLast("nettyGroupChatHandler",new NettyGroupChatServerHandler());
                   }
               });
       try {
           //启动服务
           ChannelFuture future = bootstrap.bind(new InetSocketAddress("127.0.0.1", 8888)).sync();
           future.channel().closeFuture().sync();
       } catch (InterruptedException e) {
           e.printStackTrace();
       }finally {
           //关闭资源
           bossGroup.shutdownGracefully();
           workGroup.shutdownGracefully();
       }
   }
}

服务端处理器我们通过继承 SimpleChannelInboundHandler 入站Handler来处理消息。

其中提供了几个方法

  • channelRead0 ():读取消息
  • handlerRemoved ():客户端断开
  • handlerAdded ():客户端建立连接
  • exceptionCaught ():出现异常

具体代码如下

public class NettyGroupChatServerHandler extends SimpleChannelInboundHandler<String> {
    //把所有客户端的channel保存起来
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        String message = dateFormat.format(new Date())+":%s:"+msg;
        //消息转发给所有的客户端
        channels.forEach(channel -> {
            if(channel == ctx.channel()){
                String sendMsg = String.format(message, "我");
                channel.writeAndFlush(sendMsg);
                System.out.println(sendMsg);

            }else{
                String sendMsg = String.format(message, ctx.channel().remoteAddress());
                channel.writeAndFlush(sendMsg);
                System.out.println(sendMsg);
            }
        });
    }
    //断开连接 , 把消息广播给其他客户端
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        String message = dateFormat.format(new Date())+":"+ctx.channel().remoteAddress()+":断开连接";
        channels.writeAndFlush(message);
        System.out.println(message);
    }
    //建立连接
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        String message = dateFormat.format(new Date())+":"+ctx.channel().remoteAddress()+":加入聊天室";
        //自动把消息广播给其客户端
        channels.writeAndFlush(message);
        //客户端加入组
        channels.add(ctx.channel());
        System.out.println(message);
    }
    //出现异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
    }
    //客户端退出
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String message = dateFormat.format(new Date())+":"+ctx.channel().remoteAddress()+":退出聊天室";
        System.out.println(message);
    }
    //客户端出于活动
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = dateFormat.format(new Date())+":"+ctx.channel().remoteAddress()+":上线啦";
        System.out.println(message);
    }
}

客户端

客户端需要创建一个循环事件组,然后通过BootStrap去启动,然后扫描键盘输入作为数据源来把信息发送给服务端

public class NettyGroupChatClient {
    public static void main(String[] args) {
        new NettyGroupChatClient().start();
    }
    public void start(){
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        //解码器
                        channel.pipeline().addLast("decoder", new StringDecoder());
                        //编码器
                        channel.pipeline().addLast("encoder",new StringEncoder());
                        //处理器
                        channel.pipeline().addLast("nettyGroupChatClientHandler",new NettyGroupChatClientHandler());
                    }
                });
        try {
            ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8888)).sync();
            //通道
            Channel channel = future.channel();
            //扫描键盘输入
            Scanner scanner = new Scanner(System.in);
            while(scanner.hasNextLine()){
                String message = scanner.nextLine();
                //发送数据
                channel.writeAndFlush(message);
            }
        } catch (InterruptedException e) {
        }finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}

对于处理器只需要接收服务端转发过来的消息即可

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

启动服务端和多个客户端,效果如下

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

到此这篇关于从入门到超神系列的Netty群聊系统的文章就介绍到这了,更多相关Netty群聊系统内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • JRebel2023.3 插件使用及安装步骤详解

    JRebel2023.3 插件使用及安装步骤详解

    JRebel是一款JVM插件,它使得Java代码修改后不用重启系统,立即生效,IDEA上原生是不支持热部署的,一般更新了 Java 文件后要手动重启 Tomcat 服务器,才能生效,浪费时间浪费生命,目前对于idea热部署最好的解决方案就是安装JRebel插件,本文分步骤介绍的非常详细,一起看看吧
    2023-08-08
  • Java如何获取Cookie和Session

    Java如何获取Cookie和Session

    Cookie 和 Session之间主要是通过 SessionId 关联起来的, SessionId是 Cookie 和 Session 之间的桥梁,这篇文章主要介绍了Java获取Cookie和Session的方法,需要的朋友可以参考下
    2024-01-01
  • lombok注解介绍小结

    lombok注解介绍小结

    lombok是一个可以帮助我们简化java代码编写的工具类,这篇文章主要介绍了lombok注解介绍小结,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • 如何使用 IntelliJ IDEA 编写 Spark 应用程序(Scala + Maven)

    如何使用 IntelliJ IDEA 编写 Spark 应用程序(Sc

    本教程展示了如何在IntelliJIDEA中使用Maven编写和运行一个简单的Spark应用程序(例如WordCount程序),本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2024-11-11
  • SpringBoot实现异步事件Event详解

    SpringBoot实现异步事件Event详解

    这篇文章主要介绍了SpringBoot实现异步事件Event详解,异步事件的模式,通常将一些非主要的业务放在监听器中执行,因为监听器中存在失败的风险,所以使用的时候需要注意,需要的朋友可以参考下
    2023-11-11
  • java将m3u8格式转成视频文件的方法

    java将m3u8格式转成视频文件的方法

    这篇文章主要介绍了如何java将m3u8格式转成视频文件,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-03-03
  • Mybatis传递多个参数的三种实现方法

    Mybatis传递多个参数的三种实现方法

    这篇文章主要介绍了Mybatis传递多个参数的三种实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • Intellij IDEA 最全超实用快捷键整理(长期更新)

    Intellij IDEA 最全超实用快捷键整理(长期更新)

    这篇文章主要介绍了Intellij IDEA 最全实用快捷键整理(长期更新),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02
  • SpringBoot 集成 Nebula的操作过程

    SpringBoot 集成 Nebula的操作过程

    这篇文章主要介绍了SpringBoot 集成 Nebula的操作过程,通过示例代码介绍了java 环境下如何对 Nebula Graph 进行操作,感兴趣的朋友跟随小编一起看看吧
    2024-05-05
  • idea tomcat乱码问题的解决及相关设置的步骤

    idea tomcat乱码问题的解决及相关设置的步骤

    这篇文章主要介绍了idea tomcat乱码问题的解决及相关设置的步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11

最新评论