使用Netty实现多客户端连接并且互相通信

使用netty实现多客户端连接并且互相通信的需求:

1.服务器启动,n多个客户端与服务器进行连接,一个客户端上线之后,服务器端控制台会打印xx上线了,其他的客户端控制台打印xx上线了。如果一个客户端下线了,服务器端的控制台上打印,xx下线了,其他的客户端控制台打印xx下线了。

2.多个客户端都上线之后,一个客户端(比如说A)给服务端发送消息,那么客户端(比如说A,B,C,包括自己本身)都会收到消息,对于A来说,会标志此消息是自己发送自己的,其他的客户端则会收到具体的消息。

服务器代码:

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 MyChatServer {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup wokerGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,wokerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new MyChatServerInializer());

            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            wokerGroup.shutdownGracefully();
        }
    }
}

服务器端初始化Initializer

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 MyChatServerInializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        //分割接收到的Bytebu,根据指定的分割符
        pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new MyChatServerHandler());
    }
}

自定义Handler:

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 MyChatServerHandler extends SimpleChannelInboundHandler<String>{

    //保留所有与服务器建立连接的channel对象,这边的GlobalEventExecutor在写博客的时候解释一下,看其doc
    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();  //其实相当于一个connection

        /**
         * 调用channelGroup的writeAndFlush其实就相当于channelGroup中的每个channel都writeAndFlush
         *
         * 先去广播,再将自己加入到channelGroup中
         */
        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");

        //验证一下每次客户端断开连接,连接自动地从channelGroup中删除调。
        System.out.println(channelGroup.size());
        //当客户端和服务端断开连接的时候,下面的那段代码netty会自动调用,所以不需要人为的去调用它
        //channelGroup.remove(channel);
    }

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

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() +" 下线了");
    }

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

客户端代码:

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 MyChatClient {
    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 MyChatClientInitializer());

            Channel channel = bootstrap.connect("localhost",8899).sync().channel();

            //标准输入
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

            //利用死循环,不断读取客户端在控制台上的输入内容
            for (;;){
                channel.writeAndFlush(bufferedReader.readLine() +"\r\n");
            }

        }finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}

客户端初始化Initializer

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 MyChatClientInitializer 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 MyChatClientHandler());
    }
}

客户端Handler:

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

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

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

启动服务器,启动第一个客户端的时候,服务器端控制台打印

/127.0.0.1:54771 上线了

第二个客户端启动,则服务器控制台打印,

/127.0.0.1:54771 上线了
/127.0.0.1:54792 上线了

此时第一个客户端打印,
【服务器】 -/127.0.0.1:54792 加入

启动第三个客户端依次可以自己验证,当我在客户端1控制台输入信息的时候,客户端1控制台打印了【自己】hi,server

hi,server
 【自己】hi,server 

其他的二个客户端控制台打印

/127.0.0.1:54771 发送的消息:hi,server 

如果其他的客户端下线之后,比如客户端1下线,服务器端控制台打印

/127.0.0.1:54771 下线了
2

其他客户端控制台打印:

【服务器】 -/127.0.0.1:54771 离开

使用命令去验证端口通信

 

16人点赞

 

netty学习

 



作者:二月_春风
链接:https://www.jianshu.com/p/adc2de3691c7
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值