不知道大家对下面的这个图标眼熟不
对,这就是netty,最近差点整疯了我的一个网络框架,下方是官网对他的描述,感兴趣大家可以去官网看一下,这不是今天的重点,接着往下看:
为啥说这玩意快把我整疯了啊,哎,好奇害死猫啊,我这人是对网络一窍不通,所以网络的东西我一般是不去触碰的,但是,最近公司的人以及各大论坛里面,netty这个技术真的是如日中天,我身边的朋友去面试的回来也说这个技术问的有点多啊,我好奇心作怪就想去试一下,然后在网上查找了很多资料和代码实现,我就觉得没啥,于是自己搭建了一下玩玩,比方说下面我要跟大家说的这个重点:netty+springboot实现 长连接 - 心跳 - 自动重连 - 通信
然后出问题了,我作为程序员的执拗,不能有bug,这就出问题了,我们先来看一下网上的源码
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 biws
* @date 2020/11/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("连接成功");
}
}
});
}
}
好了,到这里,没问题,成功实现,我就觉得这也没啥啊,这不是挺简单的嘛,难道说他们是在面试的时候问道底层源码啊,这玩意整不了 啊,可能这就是命啊,我就没关,让他执行着,喝口饮料休息一下,没想到突然就报错了,然后又好了,emmmm,这不是自己给自己找事啊
通过测试,模拟30次大约有3次失败的样子,回看源码,其实代码中存在的矛盾不难发现,就是Scanner和Channel谁的创建时间更短。可能在他的电脑上没有什么问题,但是在我这里就不行,感觉更像是在赌博,看你运气怎么样,这样那行啊,理