文章目录提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
- 一、实现netty采集jtt808协议
- 二、使用步骤
- 1.netty接入数据
- 2.jtt808协议解析
- 采用策略模式解析
- 开始解析
提示:以下是本篇文章正文内容,下面案例可供参考
一、实现netty采集jtt808协议 二、使用步骤 1.netty接入数据代码如下(示例):
io.netty netty-all 4.1.30.Final
实现netty接入jtt808协议:
import com.qycloud.iot.microserviceindoorpositioning.gps.config.GpsConfiguration;
import com.qycloud.iot.microserviceindoorpositioning.netty.utils.GpsDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@Profile("!test1") //单元测试类添加 @ActiveProfiles("test1")
public class NettyServer implements ApplicationRunner {
@Autowired
GpsConfiguration gpsConfiguration;
@Autowired
NettyServerHandler nettyServerHandler;
@Override
public void run(ApplicationArguments args)
{
// 创建对应的 线程池
// 创建Boss group
EventLoopGroup boosGroup = new NioEventLoopGroup(1);
// 创建 workgroup
EventLoopGroup workGroup = new NioEventLoopGroup();
// 创建对应的启动类
ServerBootstrap bootstrap = new ServerBootstrap();
try{
// 设置相关的配置信息
bootstrap.group(boosGroup,workGroup) // 设置对应的线程组
.channel(NioServerSocketChannel.class) // 设置对应的通道
.option(ChannelOption.SO_BACKLOG,1024) // 设置线程的连接个数
.childHandler(new ChannelInitializer() { // 设置
@Override
protected void initChannel(SocketChannel socketChannel) {
socketChannel.pipeline().addLast(new GpsDecoder()); //自定义的解码
socketChannel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
socketChannel.pipeline().addLast(nettyServerHandler);
}
});
log.info("netty服务启动了....");
// 绑定端口 启动服务
ChannelFuture channelFuture = bootstrap.bind(gpsConfiguration.getPort()).sync();
// 对关闭通道进行监听
channelFuture.channel().closeFuture().sync();
}catch (Exception e){
log.error("netty启动错误....",e);
}finally {
// 优雅停服
boosGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
import com.qycloud.iot.microserviceindoorpositioning.gps.GpsProtocolDataHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@ChannelHandler.Sharable
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
@Autowired
GpsProtocolDataHandler gpsProtocolDataHandler;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
log.info("开始解析设备,拿到的数据为-------{}" ,msg);
if (null == msg || msg.toString().isEmpty()) return;
String body = (String) msg;
gpsProtocolDataHandler.handleProtocol(ctx, body);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws InterruptedException {
// SocketAddress address = ctx.channel().remoteAddress();
// System.out.println("客户端请求到了..." + address);
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
// SocketAddress address = ctx.channel().remoteAddress();
// System.out.println("客户端请求断开..." + address);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
// ctx.writeAndFlush(hexStrToBytes("ab13"));
// writeAndFlush 是组合方法
// ctx.channel().writeAndFlush(hexStrToBytes("ab13"));
// ctx.writeAndFlush(Unpooled.copiedBuffer(rMsg,CharsetUtil.UTF_8));
}
}
netty解码,回写工具
import com.qycloud.iot.microserviceindoorpositioning.gps.utils.ByteUtils;
import com.qycloud.iot.microserviceindoorpositioning.gps.utils.GpsAnalyseUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.Locale;
@Slf4j
public class GpsDecoder extends ByteToMessageDecoder {
StringBuffer temp = new StringBuffer();
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List
import com.qycloud.iot.microserviceindoorpositioning.gps.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MyTools {
private static volatile MyTools myTools;
private MyTools() {
}
public static MyTools getInstance() {
if (null == myTools) {
synchronized (MyTools.class) {
if (null == myTools) {
myTools = new MyTools();
}
}
}
return myTools;
}
public void writeToClient(final String receiveStr, ChannelHandlerContext channel, final String mark) {
try {
ByteBuf bufff = Unpooled.buffer();//netty需要用ByteBuf传输
bufff.writeBytes(ByteUtils.hexString2Bytes(receiveStr));//对接需要16进制
channel.writeAndFlush(bufff).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
StringBuilder sb = new StringBuilder();
if (null != mark && !mark.isEmpty()) {
sb.append("【").append(mark).append("】");
}
if (future.isSuccess()) {
log.debug(sb.toString() + "回写成功" + receiveStr);
} else {
log.warn(sb.toString() + "回写失败" + receiveStr);
}
}
});
} catch (Exception e) {
e.printStackTrace();
log.warn("调用通用writeToClient()异常" + e.getMessage());
}
}
}
2.jtt808协议解析
采用策略模式解析
自定义注解
import com.qycloud.iot.microserviceindoorpositioning.gps.common.SignCode;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target( ElementType.TYPE) //注解定义到类上
@Retention( RetentionPolicy.RUNTIME) //生命周期
public @interface Sign {
// String value();
// String message() ;
SignCode value();
}
import com.qycloud.iot.microserviceindoorpositioning.gps.config.GpsConfiguration;
import com.qycloud.iot.microserviceindoorpositioning.gps.domain.GpsProtocol;
import com.qycloud.iot.microserviceindoorpositioning.gps.handle.ISign;
import com.qycloud.iot.microserviceindoorpositioning.gps.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.Set;
@Slf4j
public class SignFactory {
@Autowired
GpsConfiguration gpsConfiguration;
private static HashMap sourceMap = new HashMap<>();
static {
//反射工具包,指明扫描路径
Reflections reflections = new Reflections("com.qycloud.iot.microserviceindoorpositioning");
//获取带我们pay注解的类
Set> classSet = reflections.getTypesAnnotatedWith(Sign.class);
//根据注解的值,将全类名放到map中
for (Class clazz : classSet){
Sign pay = (Sign) clazz.getAnnotation(Sign.class);
sourceMap.put(pay.value().getCode(),clazz.getCanonicalName());
}
}
public static ISign getInstance(GpsProtocol gpsProtocol){
ISign chatType = null;
try {
//取得全类名
String className = sourceMap.get(gpsProtocol.getSignCode());
//取得类对象
Class clazz= Class.forName(className);
//======================创建对象=====================
chatType = (ISign) SpringUtils.getInterface(clazz);
}catch (Exception e){
log.error("尚未定义处理类标志:"+gpsProtocol.getSignCode()+"原始数据为:"+gpsProtocol.getRawData(),e);
}
return chatType;
}
}
public enum SignCode {
Sign_0002("0002", "终端心跳"),
Sign_0100("0100", "终端注册"),
Sign_0102("0102", "终端鉴权"),
Sign_0104("0104", "查询终端参数应答"),
Sign_0200("0200", "位置信息汇报"),
Sign_0704("0704", "定位数据批量上传"),
Sign_8001("8001", "平台通用应答"),
Sign_8100("8100", "终端注册应答"),
Sign_8104("8104", "查询终端参数"),
;
SignCode(String code, String desc) {
this.code = code;
this.desc = desc;
}
private String code;
private String desc;
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
开始解析
import com.qycloud.iot.microserviceindoorpositioning.gps.domain.GpsProtocol;
import com.qycloud.iot.microserviceindoorpositioning.gps.handle.ISign;
import com.qycloud.iot.microserviceindoorpositioning.gps.sign.SignFactory;
import com.qycloud.iot.microserviceindoorpositioning.gps.utils.GpsAnalyseUtils;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class GpsProtocolDataHandler {
public void handleProtocol(ChannelHandlerContext ctx, String oriMsg) {
try {
GpsProtocol gpsProtocol = GpsAnalyseUtils.handleGpsProtocol(oriMsg);
if (null == gpsProtocol) return;
ISign instance = SignFactory.getInstance(gpsProtocol);
if (null != instance) {
instance.handle(ctx, gpsProtocol);
}
} catch (Exception e) {
log.error("原始数据:"+oriMsg);
log.error("GPS错误信息:",e);
e.printStackTrace();
}
}
}
aa
aa
aa



