netty - springboot - 长连接 - 心跳 - 自动重连 - 通信

前言

  本博客参考自netty 实现长连接,心跳机制,以及重连

  该大佬为CN-LILU

  参考上面的博客搭建之后可以成功实现长连接、心跳及重连并且原博主可进行消息通信。但是我这里并不能进行消息通信。

  (ps:原文中在子线程创建channel的同时,主线程判断channel是否为空,我这边测试是一直失败的,也就是说我这边sendData循环1000遍之后,子线程创建channel有可能仍然没有成功。个人认为这之前应该有判断,而不是靠运气来判断主线程for的时间和子线程创建channel的时间。下面做一个简单测试:)

package com.gzky.study;

import com.gzky.study.netty.MsgPckDecode;
import com.gzky.study.netty.MsgPckEncode;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.Scanner;

/**
 * @author zhaohualuo
 * @date 2019/12/20
 **/
public class TestFor {
    private static NioEventLoopGroup worker = new NioEventLoopGroup();

    private static Channel channel;

    private static Bootstrap bootstrap;

    boolean flag = true;

    public static void main(String[] args) {

        for (int i = 0; i < 30; i++) {
            long start = System.currentTimeMillis();
            Scanner sc= new Scanner(System.in);
            long end = System.currentTimeMillis();
            long l1 = end - start;

            long start2 = System.currentTimeMillis();
            start();
            long end2 = System.currentTimeMillis();
            long l2 = end2 - start2;

            if (l1 > l2) {
                System.out.println("Scanner大,false");
            } else {
                System.out.println("true--------------");
            }
        }
    }

    private static void start() {
        bootstrap = new Bootstrap();
        bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        // TODO Auto-generated method stub
                        ChannelPipeline pipeline = ch.pipeline();

                        pipeline.addLast(new IdleStateHandler(3, 3, 5));

                        pipeline.addLast(new MsgPckDecode());

                        pipeline.addLast(new MsgPckEncode());

                    }
                });
        doConnect();
    }

    protected static void doConnect() {

        if (channel != null && channel.isActive()) {
            return;
        }
        ChannelFuture connect = bootstrap.connect("127.0.0.1", 8089);
        //实现监听通道连接的方法
        connect.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {

                if (channelFuture.isSuccess()) {
                    channel = channelFuture.channel();
                    System.out.println("连接成功");
                }
            }
        });
    }
}

在这里插入图片描述

  通过上面的测试,模拟30次大约有3次失败的样子,但是不知道为什么我一直失败·······,所以原博主的主要矛盾就是Scanner和Channel谁的创建时间更短。(我总感觉这是赌博,我测试的时候就总是不行)。

  在本公司大佬的协助下在上面博客的基础上对客户端代码进行了一定程度的改造,现在已完善通信功能!!!

  参考别人博客自己搭建,且有部分代码进行了改造的情况下,是标转载还是标原创啊(我潜意识一直以为把别人的文章复制过来的才是转载)····

  把原文和文章大佬放在本文最开始的位置以示尊重!!!

一、pom文件

<!-- 解码and编码器 -->
<!-- https://mvnrepository.com/artifact/org.msgpack/msgpack -->
<dependency>
    <groupId>org.msgpack</groupId>
    <artifactId>msgpack</artifactId>
    <version>0.6.12</version>
</dependency>
<!-- 引入netty依赖 -->
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.6.Final</version>
</dependency>

二、配置项

package com.gzky.study.netty;

/**
 * 配置项
 *
 * @author zhaohualuo
 * @date 2019/12/19
 **/
public interface TypeData {
    //客户端代码
    byte PING = 1;

    //服务端代码
    byte PONG = 2;

    //顾客
    byte CUSTOMER = 3;
}

三、消息类型分离器

package com.gzky.study.netty;

import org.msgpack.annotation.Message;

import java.io.Serializable;

/**
 * 消息类型分离器
 *
 * @author zhaohualuo
 * @date 2019/12/19
 **/
@Message
public class Model implements Serializable {

    private static final long serialVersionUID = 1L;

    //类型
    private int type;

    //内容
    private String body;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return "Model{" +
                "type=" + type +
                ", body='" + body + '\'' +
                '}';
    }
}

四、编码器

package com.gzky.study.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.msgpack.MessagePack;

/**
 * 编码器
 *
 * @author zhaohualuo
 * @date 2019/12/19
 **/
public class MsgPckEncode extends MessageToByteEncoder<Object> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf buf)
            throws Exception {
        // TODO Auto-generated method stub
        MessagePack pack = new MessagePack();

        byte[] write = pack.write(msg);

        buf.writeBytes(write);
    }
}

五、解码器

package com.gzky.study.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.msgpack.MessagePack;

import java.util.List;

/**
 * 解码器
 *
 * @author zhaohualuo
 * @date 2019/12/19
 **/
public class MsgPckDecode extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg,
                          List<Object> out) throws Exception {

        final  byte[] array;

        final int length = msg.readableBytes();

        array = new byte[length];

        msg.getBytes(msg.readerIndex(), array, 0, length);

        MessagePack pack = new MessagePack();

        out.add(pack.read(array, Model.class));

    }
}

六、公用控制器

package com.gzky.study.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 公用控制器
 *
 * @author zhaohualuo
 * @date 2019/12/19
 **/
public abstract class Middleware extends ChannelInboundHandlerAdapter {
    protected String name;
    //记录次数
    private int heartbeatCount = 0;

    //获取server and client 传入的值
    public Middleware(String name) {
        this.name = name;
    }
    /**
     *继承ChannelInboundHandlerAdapter实现了channelRead就会监听到通道里面的消息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        Model m = (Model) msg;
        int type = m.getType();
        switch (type) {
            case 1:
                sendPongMsg(ctx);
                break;
            case 2:
                System.out.println(name + " get  pong  msg  from" + ctx.channel().remoteAddress());
                break;
            case 3:
                handlerData(ctx,msg);
                break;
            default:
                break;
        }
    }

    protected abstract void handlerData(ChannelHandlerContext ctx,Object msg);

    protected void sendPingMsg(ChannelHandlerContext ctx){
        Model model = new Model();

        model.setType(TypeData.PING);

        ctx.channel().writeAndFlush(model);

        heartbeatCount++;

        System.out.println(name + " send ping msg to " + ctx.channel().remoteAddress() + "count :" + heartbeatCount);
    }

    private void sendPongMsg(ChannelHandlerContext ctx) {

        Model model = new Model();

        model.setType(TypeData.PONG);

        ctx.channel().writeAndFlush(model);

        heartbeatCount++;

        System.out.println(name +" send pong msg to "+ctx.channel().remoteAddress() +" , count :" + heartbeatCount);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception {
        IdleStateEvent stateEvent = (IdleStateEvent) evt;

        switch (stateEvent.state()) {
            case READER_IDLE:
                handlerReaderIdle(ctx);
                break;
            case WRITER_IDLE:
                handlerWriterIdle(ctx);
                break;
            case ALL_IDLE:
                handlerAllIdle(ctx);
                break;
            default:
                break;
        }
    }

    protected void handlerAllIdle(ChannelHandlerContext ctx) {
        System.err.println("---ALL_IDLE---");
    }

    protected void handlerWriterIdle(ChannelHandlerContext ctx) {
        System.err.println("---WRITER_IDLE---");
    }

    protected void handlerReaderIdle(ChannelHandlerContext ctx) {
        System.err.println("---READER_IDLE---");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        System.err.println(" ---"+ctx.channel().remoteAddress() +"----- is  action" );
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        System.err.println(" ---"+ctx.channel().remoteAddress() +"----- is  inAction");
    }
}

七、客户端

package com.gzky.study.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * Client客户端
 *
 * @author zhaohualuo
 * @date 2019/12/19
 **/
public class Client {
    private NioEventLoopGroup worker = new NioEventLoopGroup();

    private Channel channel;

    private Bootstrap bootstrap;

    boolean flag = true;

    public static void main(String[] args) {
        Client client = new Client();

        client.start();

        client.sendData();

		//通信结束,关闭客户端
        client.close();
    }

    private void close() {
        channel.close();
        worker.shutdownGracefully();
    }

    private void start() {
        bootstrap = new Bootstrap();
        bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        // TODO Auto-generated method stub
                        ChannelPipeline pipeline = ch.pipeline();

                        pipeline.addLast(new IdleStateHandler(3, 3, 5));

                        pipeline.addLast(new MsgPckDecode());

                        pipeline.addLast(new MsgPckEncode());

                        pipeline.addLast(new Client3Handler(Client.this));
                    }
                });
        doConnect();
    }

    /**
     * 连接服务端 and 重连
     */
    protected void doConnect() {

        if (channel != null && channel.isActive()) {
            return;
        }
        ChannelFuture connect = bootstrap.connect("127.0.0.1", 8089);
        //实现监听通道连接的方法
        connect.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {

                if (channelFuture.isSuccess()) {
                    channel = channelFuture.channel();
                    System.out.println("连接成功");
                } else {
                    if (flag) {
                        System.out.println("每隔2s重连....");
                        channelFuture.channel().eventLoop().schedule(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                doConnect();
                            }
                        }, 2, TimeUnit.SECONDS);
                    }
                }
            }
        });
    }

    /**
     * 向服务端发送消息
     */
    private void sendData() {
    	//创建连接成功之前停在这里等待
        while (channel == null || !channel.isActive()) {
            System.out.println("等待连接···");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("连接成功等待输入:");
        flag = true;
        Scanner sc = new Scanner(System.in);
        while (flag) {
            String nextLine = sc.nextLine();
            if ("end".equalsIgnoreCase(nextLine)) {
                flag = false;
            }
            Model model = new Model();
            model.setType(TypeData.CUSTOMER);
            model.setBody(nextLine);
            channel.writeAndFlush(model);
        }
    }
}

八、客户端控制器

package com.gzky.study.netty;

import io.netty.channel.ChannelHandlerContext;

/**
 * 客户端控制器
 *
 * @author zhaohualuo
 * @date 2019/12/19
 **/
public class Client3Handler extends Middleware {
    private Client client;

    public Client3Handler(Client client) {
        super("client");
        this.client = client;
    }

    @Override
    protected void handlerData(ChannelHandlerContext ctx, Object msg) {
        // TODO Auto-generated method stub
        Model model = (Model) msg;
        System.out.println("client  收到数据: " + model.toString());
    }
    @Override
    protected void handlerAllIdle(ChannelHandlerContext ctx) {
        // TODO Auto-generated method stub
        super.handlerAllIdle(ctx);
        sendPingMsg(ctx);
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        super.channelInactive(ctx);
        client.doConnect();
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        System.out.println(name + "exception :"+ cause.toString());
    }
}

九、服务端

package com.gzky.study.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * 服务端
 *
 * @author zhaohualuo
 * @date 2019/12/19
 **/
public class Server {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);

        EventLoopGroup workerGroup = new NioEventLoopGroup(4);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(8089)
                    .childHandler(new ChannelInitializer<Channel>() {

                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            // TODO Auto-generated method stub
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new IdleStateHandler(10,3,10));
                            pipeline.addLast(new MsgPckDecode());
                            pipeline.addLast(new MsgPckEncode());
                            pipeline.addLast(new Server3Handler());
                        }
                    });
            System.out.println("start server 8089 --");
            ChannelFuture sync = serverBootstrap.bind().sync();
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            //优雅的关闭资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}

十、服务端控制器

package com.gzky.study.netty;

import io.netty.channel.ChannelHandlerContext;

/**
 * 服务端控制器
 *
 * @author zhaohualuo
 * @date 2019/12/19
 **/
public class Server3Handler extends Middleware {
    public Server3Handler() {
        super("server");
        // TODO Auto-generated constructor stub
    }
    @Override
    protected void handlerData(ChannelHandlerContext ctx, Object msg) {
        // TODO Auto-generated method stub
        Model model  = (Model) msg;
        System.out.println("server 接收数据 : " +  model.toString());
        model.setType(TypeData.CUSTOMER);
        model.setBody("client你好,server已接收到数据:"+model.getBody());
        ctx.channel().writeAndFlush(model);
        System.out.println("server 发送数据: " + model.toString());
    }
    @Override
    protected void handlerReaderIdle(ChannelHandlerContext ctx) {
        // TODO Auto-generated method stub
        super.handlerReaderIdle(ctx);
        System.err.println(" ---- client "+ ctx.channel().remoteAddress().toString() + " reader timeOut, --- close it");
        ctx.close();
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        System.err.println( name +"  exception" + cause.toString());
    }
}

十一、测试

1、启动服务端

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

2、启动客户端

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

3、客户端发消息

在客户端控制台输入:
在这里插入图片描述
服务端控制台就可以收到hello,并且回信。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_33247435/article/details/103633227