Netty中实现多客户端连接与通信-以实现聊天室群聊功能为例(附代码下载)

场景

Netty的Socket编程详解-搭建服务端与客户端并进行数据传输:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108615023

在此基础上要实现多个客户端之间通信,实现类似群聊或者聊天室的功能。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

在上面实现的服务端与客户端通信的基础上,在src下新建com.badao.Char包,包下新建ChatServer类作为聊天室的服务端。

package com.badao.Chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class ChatServer {
    public static void main(String[] args) throws  Exception
    {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChatServerInitializer());
            //绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(70).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            //关闭事件组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

在上面中绑定70端口并添加了一个服务端的初始化器ChatServerInitializer

所以新建类ChatServerInitializer

package com.badao.Chat;


import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class ChatServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new ChatServerHandler());
    }
}

使其继承ChannelInitializer,并重写InitChannel方法,在方法中使用Netty自带的处理器进行编码的处理并最后添加一个自定义的处理器ChatServerHandler

新建处理器类ChatServerHandler

package com.badao.Chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();

        channelGroup.forEach(ch->{
            if(channel!=ch)
            {
                ch.writeAndFlush(channel.remoteAddress()+"发送的消息:"+msg+"\n");
            }
            else
            {
                ch.writeAndFlush("[自己]:"+msg+"\n");
            }
        });
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[服务器]:"+channel.remoteAddress()+"加入\n");
        channelGroup.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[服务器]:"+channel.remoteAddress()+"离开\n");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+"上线了\n");
        System.out.println("当前在线人数:"+channelGroup.size());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+"下线了\n");
        System.out.println("当前在线人数:"+channelGroup.size());
    }

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

使处理器继承SimpleChannelinboundHandler并重写channelRead0方法。

在最上面声明了一个通道组的通过 DefaultChannelGroup(GlobalEventExecutor.INSTANCE)

获取其单例,只要是建立连接的客户端都会自动添加进此通道组中。

然后只要是客户端与服务端发送消息后就会执行该方法。

在此方法中直接遍历通道组,判断通道组里面的每一个客户端是不是当前发消息的客户端。

如果是就显示自己发送消息,如果不是则获取远程地址并显示发送消息。

然后就是实现客户端的上线功能以及在线人数统计的功能。

在上面的处理器中重写channelActive方法,此方法会在通道激活即建立连接后调用

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+"上线了\n");
        System.out.println("当前在线人数:"+channelGroup.size());
    }

同理重写channelInactive方法,此方法会在断掉连接后调用

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+"下线了\n");
        System.out.println("当前在线人数:"+channelGroup.size());
    }

然后就是实现向所有的客户端广播新建客户端加入聊天室的功能

重写handlerAdded方法,此方法会在将通道添加到通道组中调用,所以在此方法中获取加入到通道组的远程地址

并使用channelGroup的writeAndFlush方法就能实现向所有建立连接的客户端发送消息,新的客户端刚上线时不用向自己

发送上线消息,所以在广播完上线消息后再讲此channel添加到channelGroup中。

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[服务器]:"+channel.remoteAddress()+"加入\n");
        channelGroup.add(channel);
    }

同理实现下线提醒需要重写handlerRemoved方法

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[服务器]:"+channel.remoteAddress()+"离开\n");
    }

但是此方法中不用手动从channelGroup中手动去掉channel,因为Netty会自动将其移除掉。

服务端搭建完成之后再搭建客户端,新建ChatClient类并编写main方法,在main方法中

package com.badao.Chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ChatClient {
    public static void main(String[] args) throws  Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {

            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new ChatClientInitializer());
            //绑定端口
            Channel channel = bootstrap.connect("localhost", 70).channel();
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            for(;;)
            {
               channel.writeAndFlush(br.readLine()+"\r\n");
            }
        } finally {
            //关闭事件组
            eventLoopGroup.shutdownGracefully();

        }
    }
}

在客户端中读取输入的内容并在一个无限循环中将输入的内容发送至服务端。

在Client中建立对服务端的连接同理也要设置一个初始化器ChatClientInitializer

新建初始化器的类ChatClientInitializer

package com.badao.Chat;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class ChatClientInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new ChatClientHandler());
    }
}

使用Netty自带的处理器对编码进行处理并添加一个自定义的处理器ChatClientHandler

新建类ChatClientHandler

package com.badao.Chat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

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

在重写的channelRead0方法中只需要将收到的消息进行输出即可。

现在运行服务端的main方法

为了能运行多个客户端在IDEA中客户端编辑

 

然后将下面的勾选上

 

然后首先运行一个客户端

 

那么在服务端中就会输出上线的客户端以及在线人数

再次运行客户端的main方法,此时服务端会输出两个客户端上线

 

同时在第二个客户端上线时第一个客户端会收到加入的提示

 

此时停掉第二个客户端即将第二个客户端下线

服务端会提示下线并更新在线人数

同时在第一个客户端会收到服务端的推送

 

再运行第二个客户端,并在控制台输入消息,回车发送

 

此时第一个客户端就会收到第二个客户端发送的消息。

 

然后第一个客户端再输入一个消息并回车

 

那么第二个客户端也能收到消息

 

示例代码下载:

https://download.csdn.net/download/BADAO_LIUMANG_QIZHI/12850228

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 使用 NETTY 实现客户端连接类时,需要创建一个 Bootstrap 对象,然后调用其 connect 方法连接到服务器。下面是一个简单的示例: ``` EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new MyClientInitializer()); // 连接到服务器 Channel channel = b.connect("localhost", 8080).sync().channel(); // 注意,在这里需要调用 closeFuture().sync() 来等待连接关闭 channel.closeFuture().sync(); } finally { group.shutdownGracefully(); } ``` 实现心跳机制的方法有很多,下面是一种常见的做法: 1. 在客户端创建一个定时任务,每隔一段时间发送一个心跳消息给服务器。 2. 在服务器端设置一个超时时间,如果在超时时间内没有收到客户端的心跳消息,则认为客户端已经断开连接。 3. 在客户端收到服务器端的响应消息后,重置超时时间。 下面是使用 Java 定时任务 Timer 和 TimerTask 实现客户端心跳的示例代码: ``` // 创建定时任务 Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // 发送心跳消息 channel.writeAndFlush(new HeartbeatMessage()); } }, 0, 5000); // 每隔 5 秒发送一次心跳 ``` 注意 ### 回答2: 使用Netty实现一个客户端连接类并实现心跳机制可以按照以下步骤进行: 首先,我们需要创建一个客户端连接类,可以继承Netty提供的ChannelInboundHandlerAdapter类,并覆盖一些方法来处理连接事件和消息传输。在这个类,我们可以实现心跳机制。 在连接建立时,可以重写channelActive()方法来发送心跳消息。可以使用Netty提供的ScheduledExecutorService来定时发送心跳消息,确保心跳间隔的准确性。在channelActive()方法,我们可以调用ScheduledExecutorService的scheduleAtFixedRate()方法来定时发送心跳消息。 在发送心跳消息时,我们可以使用Netty提供的ChannelHandlerContext类的writeAndFlush()方法来发送心跳消息到服务器。 此外,我们还需要重写channelRead()方法来处理从服务器接收到的消息。如果接收到心跳回复消息,则可以进行相关处理,例如更新上次心跳时间。 另外,我们也可以在连接状态断开时,重写channelInactive()方法来取消定时发送心跳消息的任务。 通过以上步骤,我们可以使用Netty实现一个客户端连接类,并实现心跳机制。这个连接类可以通过引入Netty的相关依赖,并使用Netty提供的API来创建客户端连接、发送心跳消息和处理服务器返回的消息。这样可以确保客户端与服务器的连接保持稳定,同时实现心跳机制可以检测服务器是否在线。 ### 回答3: 使用NETTY实现一个客户端连接类,可以通过以下步骤实现心跳机制: 首先,创建一个客户端连接类,该类继承自ChannelInboundHandlerAdapter,用于处理网络IO事件和连接状态。 在该类,需要重写一些方法来处理客户端连接、心跳发送和接收等操作。例如,重写channelActive()方法,在客户端连接成功时发送心跳消息;重写channelRead()方法,处理接收到的心跳响应消息。 然后,在连接建立时,发送心跳消息给服务器。可以使用ScheduledExecutorService来定时发送心跳消息。可以使用Netty的ChannelHandlerContext来获取客户端连接通道,并通过该通道发送消息给服务器。 在发送心跳消息之后,可以设置一个定时器,定时检测是否收到服务器的心跳响应消息。如果在指定时间内没有收到响应,可以认为与服务器的连接出现问题,可以关闭客户端连接。 需要注意的是,在每次接收到服务器的心跳响应消息时,可以重置定时器,以保证连接的稳定性。 此外,还可以在客户端连接实现异常处理方法,例如channelInactive()方法,用于处理服务器主动关闭连接或网络异常等情况。在这种情况下,可以重新连接服务器或者执行一些清理操作。 总之,使用NETTY实现一个客户端连接类,并结合定时器和异常处理方法,可以实现一个稳定的心跳机制,用于保持客户端与服务器的连接

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值