欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-03-25 23:41:26
目录服务端服务端一样的需要创建bossgroup 和 workgroup , 然后使用serverbootstrap 来配置netty和启动netty。public class nettygroupc...

服务端

服务端一样的需要创建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群聊系统
从入门到超神进阶的Netty群聊系统

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

相关标签: Netty 群聊系统