写点什么

你敢信?就是这个 Netty 的网络框架差点把我整疯了,哭 jj

用户头像
996小迁
关注
发布于: 2020 年 12 月 09 日
你敢信?就是这个Netty的网络框架差点把我整疯了,哭jj



不知道大家对下面的这个图标眼熟不





对,这就是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谁的创建时间更短。可能在他的电脑上没有什么问题,但是在我这里就不行,感觉更像是在赌博,看你运气怎么样,这样那行啊,理工科的男孩子怎么能靠赌博呢?



但是,咋整,我就在这一块就是一个渣渣啊,没办法,最后还是求助了公司的大神,幸好代码量不是特别大,抽了个周末的下午,俺俩一起在原有的代码基础上对客户端进行可以定程度的改造,现在所有的功能都已经实现,下面附上改进后的代码,有需要的朋友可以自己动手实现一下



还是建议实现一下,毕竟可能我这里可以了,但是在你的pc端又会有其他的而不一样的问题,当然了,要是有云服务器测试一下更 不错



一、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 biws
* @date 2020/11/20
**/
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 biws
* @date 2020/11/20
**/
@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 biws
* @date 2020/11/20
**/
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 biws
* @date 2020/11/20
**/
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 biws
* @date 2020/11/20
**/
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 biws
* @date 2020/11/20
**/
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 biws
* @date 2020/11/20
**/
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 biws
* @date 2020/11/20
**/
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 biws
* @date 2020/11/20
**/
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,并且回信。





好了,到这里,netty - springboot - 长连接 - 心跳 - 自动重连 - 通信就完成了,不知道你实现了没有,建议你可以先收藏,等有时间了自己实现一下,尤其是刚接触的,觉得写得还不错的,可以转发一下,让更多人看见,谢谢



新的技术学习必定是充满BUG的,但是,解决了就是一片光明,这样一点点的改BUG中,剩下的就是你成长的路径



希望可以对大家有帮助,喜欢的小伙伴可以关注公众号:小迁不秃头,每天不定时更新,干货满满!

用户头像

996小迁

关注

我就是我 2020.10.13 加入

5年Java开发经验

评论

发布
暂无评论
你敢信?就是这个Netty的网络框架差点把我整疯了,哭jj