前言
本博客參考自: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,並且回信。