package com.central.core.socket.netty.util;
import com.central.common.feign.CYService;
import com.central.common.redis.template.RedisRepository;
import com.central.common.utils.EncryptUtilCy;
import com.central.common.whtyUtils.StringUtils;
import com.central.core.socket.netty.repository.TcpChannelRepositoryCy;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Description: netty 客户端用于连接其他netty服务端
* @Author: chengbo
* @Date: 2021/8/30
*/
@Component
@Slf4j
public class NettyClient {
@Value("${chengyan.port}")
private int SERVER_PORT;
@Value("${chengyan.ip}")
private String SERVER_IP;
@Value("${chengyan.flag}")
private String FLAG;
private String sendMsg = "";
private String terminalsId = null;
private String iccid = null;
@Autowired
TcpChannelRepositoryCy tcpChannelRepositoryCy;
@Autowired
EncryptUtilCy encryptUtilCy;
@Autowired
private CYService cyService;
@Autowired
private RedisRepository redisRepository;
@Autowired
private CyUtil cyUtil;
//1. 创建线程组: 只需要一个线程组用于实际处理(网络通信的读写)
private final EventLoopGroup workGroup = new NioEventLoopGroup(4, new ThreadFactory() {
private AtomicInteger threadIndex = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "NettyClientCodecThread_" + this.threadIndex.incrementAndGet());
}
});
private final Bootstrap b = new Bootstrap();
public NettyClient() {
init();
}
public void init() {
//2 通过辅助类去构造server/client
b.group(workGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.option(ChannelOption.SO_RCVBUF, 1024 * 32)
.option(ChannelOption.SO_SNDBUF, 1024 * 32)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//ch.pipeline().addLast(new ClientHandler()); //1
ByteBuf delimiter = Unpooled.copiedBuffer("\r\n".getBytes());
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024 * 1024, delimiter));
ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));// String解码。
ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));// String解码。
// //todo 心跳设置
ch.pipeline().addLast(new IdleStateHandler(0, 2, 0, TimeUnit.SECONDS));
ch.pipeline().addLast(new MyChannelHandlerAdapter());
}
});
}
private void newThread() {
try {
//服务器端绑定端口并启动服务
ChannelFuture cf = b.connect(SERVER_IP, SERVER_PORT).sync();
log.info("连接netty " + this.terminalsId + " id: " + cf.channel().id());
sendDataToServer(cf.channel());
//使用channel级别的监听close端口 阻塞的方式
//map.put("")
// sendDataToServer(cf.channel());
cf.channel().closeFuture().sync();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public Boolean connectServerAfterClose(String terminalsId) {
log.info("成研关闭netty 参数 terminalsId: " + terminalsId);
this.terminalsId = terminalsId;
if (Objects.nonNull(tcpChannelRepositoryCy.get(this.terminalsId))) {
Channel channel = tcpChannelRepositoryCy.get(this.terminalsId);
log.info("有通道:terminalsId " + terminalsId + " id: " + channel.id());
if (channel.isActive()) {
log.info("有通道活跃:terminalsId " + terminalsId + " id: " + channel.id());
channel.close();
tcpChannelRepositoryCy.remove(terminalsId);
log.info("已关闭通道:terminalsId " + terminalsId + " id: " + channel.id());
}
}
return true;
}
public void connectServer2(String terminalsId, String msg) {
log.info("成研连接netty 参数 terminalsId: " + terminalsId + " msg" + msg);
this.terminalsId = terminalsId;
this.sendMsg = toCyContent(msg);
log.info("成研连接netty 参数 加上固定参数后msg" + this.sendMsg);
if (Objects.nonNull(tcpChannelRepositoryCy.get(this.terminalsId))) {
Channel channel = tcpChannelRepositoryCy.get(this.terminalsId);
log.info("有通道:terminalsId " + terminalsId + " id: " + channel.id());
if (channel.isActive()) {
log.info("有通道活跃:terminalsId " + terminalsId + " id: " + channel.id());
channel.writeAndFlush(this.sendMsg);
}
}
}
// Netty作为客户端,发起对服务器端的连接请求。
public void connectServer(String terminalsId, String msg, String iccid) {
log.info("成研连接netty 参数 terminalsId: " + terminalsId + " msg" + msg);
this.terminalsId = terminalsId;
this.sendMsg = toCyContent(msg);
this.iccid = iccid;
log.info("成研连接netty 参数 加上固定参数后msg:" + this.sendMsg);
if (Objects.nonNull(tcpChannelRepositoryCy.get(this.terminalsId))) {
Channel channel = tcpChannelRepositoryCy.get(this.terminalsId);
log.info("有通道:terminalsId " + terminalsId + " id: " + channel.id());
if (channel.isActive()) {
//
String isSuccess = "";
if (redisRepository.get(terminalsId + ":ISDEVICELOGINSUCCESS") != null) {
isSuccess = (String) redisRepository.get(terminalsId + ":ISDEVICELOGINSUCCESS");
//如果登录失败 进行处理 0 失败 1 成功
if ("0".equals(isSuccess)) {
channel.writeAndFlush(toCyContent(cyUtil.getDeviceLoginMsg(terminalsId, this.iccid)));
}
} else {
channel.writeAndFlush(toCyContent(cyUtil.getDeviceLoginMsg(terminalsId, this.iccid)));
}
channel.writeAndFlush(this.sendMsg);
} else {
newThread();
}
} else {
newThread();
}
}
/**
* 发送数据到服务器端。
*
* @throws Exception
*/
public void sendDataToServer(Channel channel) throws Exception {
//登录上报 进行登录上报
log.info("发送登录" + cyUtil.getDeviceLoginMsg(this.terminalsId, this.iccid) + " id: " + channel.id());
if (StringUtils.isNotEmpty(cyUtil.getDeviceLoginMsg(this.terminalsId, this.iccid))) {
channel.writeAndFlush(toCyContent(cyUtil.getDeviceLoginMsg(this.terminalsId, this.iccid)));
}
if (StringUtils.isNotEmpty(this.sendMsg)) {
log.info("sendDataToServer msg: " + this.sendMsg);
channel.writeAndFlush(this.sendMsg);
}
}
@ChannelHandler.Sharable
private class MyChannelHandlerAdapter extends ChannelInboundHandlerAdapter {
// 连接激活。
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
log.info("channelActive:" + ctx.channel().remoteAddress() + " id: " + ctx.channel().id());
log.info("terminalsId 为:" + terminalsId);
log.info("channel 为:" + ctx.channel().id());
tcpChannelRepositoryCy.put(terminalsId, ctx.channel());
log.info("打出日志是否装入:" + tcpChannelRepositoryCy.get(terminalsId));
// 连接可用激活后,Netty开始往服务器端发送数据。
//sendDataToServer(ctx.channel());
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
//Thread.sleep(2000);
if (tcpChannelRepositoryCy.get(terminalsId) != null) {
if (StringUtils.equals(tcpChannelRepositoryCy.get(terminalsId).id().toString(), ctx.channel().id().toString())) {
tcpChannelRepositoryCy.remove(terminalsId);
log.info("tcpChannelRepositoryCy移除:" + terminalsId);
}
}
log.info("channelInactive:" + ctx.channel().remoteAddress() + " id: " + ctx.channel().id());
// boolean isChannelActive = true;
// tcpChannelRepositoryCy.put(terminalsId, ctx.channel());
// if(null == NettyClient.socketChannel || !NettyClient.socketChannel.isActive()){
// isChannelActive = false;
// }
// if(reconnect && false){
// logger.info("链接关闭,将进行重连");
//
// if (attempts < NettyConstant.RET_CONNECT_TIME) {
// int timeout = 60;
// timer.newTimeout(this, timeout,TimeUnit.SECONDS);
// }
// }
// else
// {
// logger.info("链接关闭");
// }
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
log.info("成研解密前msg: " + msg);
String allcontent = encryptUtilCy.decrypt((String) msg);
log.info("成研解密后msg: " + allcontent);
String result = cyService.deviceCommandReceive(allcontent);
log.info("成研解析后result: " + result);
String deMsg = allcontent.substring(1, allcontent.length() - 1);
String[] splitData = deMsg.split(StringUtils.escapeExprSpecialWord(","));
String imei = splitData[0];
String commandType = splitData[3];
String data = splitData[7];
if ("SET_SERVER_INFO".equals(commandType)) {
ctx.writeAndFlush(toCyContent(result));
} else if ("DEVICE_LOGIN".equals(commandType)) {
//如果登录失败 进行处理 0 失败 1 成功
if ("1@0@0".equals(data)) {
redisRepository.set(imei + ":ISDEVICELOGINSUCCESS", "0");
} else {
redisRepository.set(imei + ":ISDEVICELOGINSUCCESS", "1");
}
} else if ("SET_SMS_INTERCEPT".equals(commandType)) {
ctx.writeAndFlush(toCyContent(result));
}
//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
//返回16进制到客户端
} catch (Exception e) {
log.error(e.getMessage(), e);
}
super.channelRead(ctx, msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
super.channelReadComplete(ctx);
// tcpChannelRepositoryCy.remove(terminalsId);
log.info(ctx.channel().remoteAddress() + "读写完成" + " id: " + ctx.channel().id());
}
@Override
//todo
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
int count = 0;
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
switch (e.state()) {
case WRITER_IDLE:
// if (Objects.nonNull(redisRepository.get(String.valueOf(ctx.channel().id())))) {
// count = Integer.valueOf(String.valueOf(redisRepository.get(String.valueOf(ctx.channel().id()))));
// }
// log.info("当前通道:" + ctx.channel().id() + "超时次数" + count);
// count++; // 读空闲的计数加1
// log.info("当前通道:" + ctx.channel().id() + "超时次数+1后" + count);
// redisRepository.set(String.valueOf(ctx.channel().id()), count);
break;
default:
break;
}
}
// if (count > 3) {
// log.info(" ----------------->[client]写空闲超过3次,关闭连接");
// redisRepository.del(String.valueOf(ctx.channel().id()));
// ctx.channel().writeAndFlush("im out");
// ctx.channel().close();
// }
}
}
public String toCyContent(String msg) {
if (StringUtils.isNotEmpty(msg)) {
return this.encryptUtilCy.encrypt(msg) + FLAG + "\r\n";
}
return msg;
}
}
成研nettyUtil
最新推荐文章于 2023-12-11 20:07:34 发布