不知道大家对下面的这个图标眼熟不
对,这就是 netty,最近差点整疯了我的一个网络框架,下方是官网对他的描述,感兴趣大家可以去官网看一下,这不是今天的重点,接着往下看:
为啥说这玩意快把我整疯了啊,哎,好奇害死猫啊,我这人是对网络一窍不通,所以网络的东西我一般是不去触碰的,但是,最近公司的人以及各大论坛里面,netty 这个技术真的是如日中天,我身边的朋友去面试的回来也说这个技术问的有点多啊,我好奇心作怪就想去试一下,然后在网上查找了很多资料和代码实现,我就觉得没啥,于是自己搭建了一下玩玩,比方说下面我要跟大家说的这个重点:netty+springboot 实现 长连接 - 心跳 - 自动重连 - 通信
关注公众号:Java 架构师联盟,每日更新技术好文
然后出问题了,我作为程序员的执拗,不能有 bug,这就出问题了,我们先来看一下网上的源码
 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;
   复制代码
 
     private static NioEventLoopGroup worker = new NioEventLoopGroup();
   复制代码
 
     private static Channel channel;
   复制代码
 
     private static Bootstrap bootstrap;
   复制代码
 
     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 start2 = System.currentTimeMillis();
   复制代码
 
             long end2 = System.currentTimeMillis();
   复制代码
 
                 System.out.println("Scanner大,false");
   复制代码
 
                 System.out.println("true--------------");
   复制代码
 
     private static void start() {
   复制代码
 
         bootstrap = new Bootstrap();
   复制代码
 
                 .channel(NioSocketChannel.class)
   复制代码
 
                 .option(ChannelOption.TCP_NODELAY, true)
   复制代码
 
                 .handler(new ChannelInitializer<Channel>() {
   复制代码
 
                     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());
   复制代码
 
     protected static void doConnect() {
   复制代码
 
         if (channel != null && channel.isActive()) {
   复制代码
 
         ChannelFuture connect = bootstrap.connect("127.0.0.1", 8089);
   复制代码
 
         connect.addListener(new ChannelFutureListener() {
   复制代码
 
             public void operationComplete(ChannelFuture channelFuture) throws Exception {
   复制代码
 
                 if (channelFuture.isSuccess()) {
   复制代码
 
                     channel = channelFuture.channel();
   复制代码
 
                     System.out.println("连接成功");
   复制代码
 
好了,到这里,没问题,成功实现,我就觉得这也没啥啊,这不是挺简单的嘛,难道说他们是在面试的时候问道底层源码啊,这玩意整不了 啊,可能这就是命啊,我就没关,让他执行着,喝口饮料休息一下,没想到突然就报错了,然后又好了,emmmm,这不是自己给自己找事啊
通过测试,模拟 30 次大约有 3 次失败的样子,回看源码,其实代码中存在的矛盾不难发现,就是 Scanner 和 Channel 谁的创建时间更短。可能在他的电脑上没有什么问题,但是在我这里就不行,感觉更像是在赌博,看你运气怎么样,这样那行啊,理工科的男孩子怎么能靠赌博呢?
但是,咋整,我就在这一块就是一个渣渣啊,没办法,最后还是求助了公司的大神,幸好代码量不是特别大,抽了个周末的下午,俺俩一起在原有的代码基础上对客户端进行可以定程度的改造,现在所有的功能都已经实现,下面附上改进后的代码,有需要的朋友可以自己动手实现一下
还是建议实现一下,毕竟可能我这里可以了,但是在你的 pc 端又会有其他的而不一样的问题,当然了,要是有云服务器测试一下更 不错
一、pom 文件
 <!-- https://mvnrepository.com/artifact/org.msgpack/msgpack -->
   复制代码
 
     <groupId>org.msgpack</groupId>
   复制代码
 
     <artifactId>msgpack</artifactId>
   复制代码
 
     <version>0.6.12</version>
   复制代码
 
     <groupId>io.netty</groupId>
   复制代码
 
     <artifactId>netty-all</artifactId>
   复制代码
 
     <version>4.1.6.Final</version>
   复制代码
 
二、配置项
 package com.gzky.study.netty;
   复制代码
 
 public interface TypeData {
   复制代码
 
三、消息类型分离器
 package com.gzky.study.netty;
   复制代码
 
 import org.msgpack.annotation.Message;
   复制代码
 
 import java.io.Serializable;
   复制代码
 
 public class Model implements Serializable {
   复制代码
 
     private static final long serialVersionUID = 1L;
   复制代码
 
     public void setType(int type) {
   复制代码
 
     public String getBody() {
   复制代码
 
     public void setBody(String body) {
   复制代码
 
     public String toString() {
   复制代码
 
                 ", 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;
   复制代码
 
 public class MsgPckEncode extends MessageToByteEncoder<Object> {
   复制代码
 
     protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf buf)
   复制代码
 
         // TODO Auto-generated method stub
   复制代码
 
         MessagePack pack = new MessagePack();
   复制代码
 
         byte[] write = pack.write(msg);
   复制代码
 
五、解码器
 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;
   复制代码
 
 public class MsgPckDecode extends MessageToMessageDecoder<ByteBuf> {
   复制代码
 
     protected void decode(ChannelHandlerContext ctx, ByteBuf msg,
   复制代码
 
                           List<Object> out) throws Exception {
   复制代码
 
         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;
   复制代码
 
 public abstract class Middleware extends ChannelInboundHandlerAdapter {
   复制代码
 
     private int heartbeatCount = 0;
   复制代码
 
     //获取server and client 传入的值
   复制代码
 
     public Middleware(String name) {
   复制代码
 
      *继承ChannelInboundHandlerAdapter实现了channelRead就会监听到通道里面的消息
   复制代码
 
     public void channelRead(ChannelHandlerContext ctx, Object msg)
   复制代码
 
                 System.out.println(name + " get  pong  msg  from" + ctx.channel().remoteAddress());
   复制代码
 
     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);
   复制代码
 
         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);
   复制代码
 
         System.out.println(name +" send pong msg to "+ctx.channel().remoteAddress() +" , count :" + heartbeatCount);
   复制代码
 
     public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
   复制代码
 
         IdleStateEvent stateEvent = (IdleStateEvent) evt;
   复制代码
 
         switch (stateEvent.state()) {
   复制代码
 
     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---");
   复制代码
 
     public void channelActive(ChannelHandlerContext ctx) throws Exception {
   复制代码
 
         // TODO Auto-generated method stub
   复制代码
 
         System.err.println(" ---"+ctx.channel().remoteAddress() +"----- is  action" );
   复制代码
 
     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;
   复制代码
 
     private NioEventLoopGroup worker = new NioEventLoopGroup();
   复制代码
 
     private Bootstrap bootstrap;
   复制代码
 
     public static void main(String[] args) {
   复制代码
 
         Client client = new Client();
   复制代码
 
         worker.shutdownGracefully();
   复制代码
 
         bootstrap = new Bootstrap();
   复制代码
 
                 .channel(NioSocketChannel.class)
   复制代码
 
                 .option(ChannelOption.TCP_NODELAY, true)
   复制代码
 
                 .handler(new ChannelInitializer<Channel>() {
   复制代码
 
                     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));
   复制代码
 
     protected void doConnect() {
   复制代码
 
         if (channel != null && channel.isActive()) {
   复制代码
 
         ChannelFuture connect = bootstrap.connect("127.0.0.1", 8089);
   复制代码
 
         connect.addListener(new ChannelFutureListener() {
   复制代码
 
             public void operationComplete(ChannelFuture channelFuture) throws Exception {
   复制代码
 
                 if (channelFuture.isSuccess()) {
   复制代码
 
                     channel = channelFuture.channel();
   复制代码
 
                     System.out.println("连接成功");
   复制代码
 
                         System.out.println("每隔2s重连....");
   复制代码
 
                         channelFuture.channel().eventLoop().schedule(new Runnable() {
   复制代码
 
                                 // TODO Auto-generated method stub
   复制代码
 
     private void sendData() {
   复制代码
 
         while (channel == null || !channel.isActive()) {
   复制代码
 
             System.out.println("等待连接···");
   复制代码
 
             } catch (InterruptedException e) {
   复制代码
 
         System.out.println("连接成功等待输入:");
   复制代码
 
         Scanner sc = new Scanner(System.in);
   复制代码
 
             String nextLine = sc.nextLine();
   复制代码
 
             if ("end".equalsIgnoreCase(nextLine)) {
   复制代码
 
             Model model = new Model();
   复制代码
 
             model.setType(TypeData.CUSTOMER);
   复制代码
 
             channel.writeAndFlush(model);
   复制代码
 
八、客户端控制器
 package com.gzky.study.netty;
   复制代码
 
 import io.netty.channel.ChannelHandlerContext;
   复制代码
 
 public class Client3Handler extends Middleware {
   复制代码
 
     public Client3Handler(Client client) {
   复制代码
 
     protected void handlerData(ChannelHandlerContext ctx, Object msg) {
   复制代码
 
         // TODO Auto-generated method stub
   复制代码
 
         Model model = (Model) msg;
   复制代码
 
         System.out.println("client  收到数据: " + model.toString());
   复制代码
 
     protected void handlerAllIdle(ChannelHandlerContext ctx) {
   复制代码
 
         // TODO Auto-generated method stub
   复制代码
 
         super.handlerAllIdle(ctx);
   复制代码
 
     public void channelInactive(ChannelHandlerContext ctx) throws Exception {
   复制代码
 
         // TODO Auto-generated method stub
   复制代码
 
         super.channelInactive(ctx);
   复制代码
 
     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
   复制代码
 
         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;
   复制代码
 
     public static void main(String[] args) {
   复制代码
 
         EventLoopGroup bossGroup = new NioEventLoopGroup(1);
   复制代码
 
         EventLoopGroup workerGroup = new NioEventLoopGroup(4);
   复制代码
 
             ServerBootstrap serverBootstrap = new ServerBootstrap();
   复制代码
 
             serverBootstrap.group(bossGroup, workerGroup)
   复制代码
 
                     .channel(NioServerSocketChannel.class)
   复制代码
 
                     .childHandler(new ChannelInitializer<Channel>() {
   复制代码
 
                         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
   复制代码
 
             bossGroup.shutdownGracefully();
   复制代码
 
             workerGroup.shutdownGracefully();
   复制代码
 
十、服务端控制器
 package com.gzky.study.netty;
   复制代码
 
 import io.netty.channel.ChannelHandlerContext;
   复制代码
 
 public class Server3Handler extends Middleware {
   复制代码
 
     public Server3Handler() {
   复制代码
 
         // TODO Auto-generated constructor stub
   复制代码
 
     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());
   复制代码
 
     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");
   复制代码
 
     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
   复制代码
 
         System.err.println( name +"  exception" + cause.toString());
   复制代码
 
十一、测试
1、启动服务端
2、启动客户端
3、客户端发消息
在客户端控制台输入:
服务端控制台就可以收到 hello,并且回信。
好了,到这里,netty - springboot - 长连接 - 心跳 - 自动重连 - 通信就完成了,不知道你实现了没有,建议你可以先收藏,等有时间了自己实现一下,尤其是刚接触的,觉得写得还不错的,可以转发一下,让更多人看见,谢谢
新的技术学习必定是充满 BUG 的,但是,解决了就是一片光明,这样一点点的改 BUG 中,剩下的就是你成长的路径
评论