update 电单车协议

This commit is contained in:
Guoqs
2024-07-15 11:33:11 +08:00
parent 450d6799a6
commit 2186b3e857
8 changed files with 192 additions and 69 deletions

View File

@@ -14,11 +14,11 @@ public class StartAndLengthFieldFrameDecoder extends ByteToMessageDecoder {
private static final int HEADER_LENGTH_68 = 1; // 68 包头的长度
// 起始标志
private int HEAD_DATA;
// private int HEAD_DATA;
public StartAndLengthFieldFrameDecoder(int HEAD_DATA) {
this.HEAD_DATA = HEAD_DATA;
}
// public StartAndLengthFieldFrameDecoder(int HEAD_DATA) {
// this.HEAD_DATA = HEAD_DATA;
// }
/**
* <pre>
@@ -26,62 +26,62 @@ public class StartAndLengthFieldFrameDecoder extends ByteToMessageDecoder {
* 表示数据的长度contentLengthint类型占据1个字节.
* </pre>
*/
public final int BASE_LENGTH = 1 + 1;
// public final int BASE_LENGTH = 1 + 1;
// @Override
protected void decode2(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
// 可读长度必须大于基本长度
if (buffer.readableBytes() <= BASE_LENGTH) {
log.warn("可读字节数:{}小于基础长度:{}", buffer.readableBytes(), BASE_LENGTH);
return;
}
// 记录包头开始的index
int beginReader;
while (true) {
// 获取包头开始的index
beginReader = buffer.readerIndex();
// log.info("包头开始的index:{}", beginReader);
// 标记包头开始的index
buffer.markReaderIndex();
// 读到了协议的开始标志结束while循环
if (buffer.getUnsignedByte(beginReader) == HEAD_DATA) {
// log.info("读到了协议的开始标志结束while循环 byte:{}, HEAD_DATA:{}", buffer.getUnsignedByte(beginReader), HEAD_DATA);
break;
}
// 未读到包头,略过一个字节
// 每次略过,一个字节,去读取,包头信息的开始标记
buffer.resetReaderIndex();
buffer.readByte();
// 当略过,一个字节之后,
// 数据包的长度,又变得不满足
// 此时,应该结束。等待后面的数据到达
if (buffer.readableBytes() < BASE_LENGTH) {
log.debug("数据包的长度不满足 readableBytes:{}, BASE_LENGTH:{}", buffer.readableBytes(), BASE_LENGTH);
return;
}
}
// 消息的长度
int length = buffer.getUnsignedByte(beginReader + 1);
// 判断请求数据包数据是否到齐
if (buffer.readableBytes() < length + 4) {
// log.info("请求数据包数据没有到齐,还原读指针 readableBytes:{}, 消息的长度:{}", buffer.readableBytes(), length);
// 还原读指针
buffer.readerIndex(beginReader);
return;
}
// 读取data数据
byte[] data = new byte[length + 4];
buffer.readBytes(data);
ByteBuf frame = buffer.retainedSlice(beginReader, length + 4);
buffer.readerIndex(beginReader + length + 4);
out.add(frame);
}
// protected void decode2(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
// // 可读长度必须大于基本长度
// if (buffer.readableBytes() <= BASE_LENGTH) {
// log.warn("可读字节数:{}小于基础长度:{}", buffer.readableBytes(), BASE_LENGTH);
// return;
// }
//
// // 记录包头开始的index
// int beginReader;
//
// while (true) {
// // 获取包头开始的index
// beginReader = buffer.readerIndex();
// // log.info("包头开始的index:{}", beginReader);
// // 标记包头开始的index
// buffer.markReaderIndex();
// // 读到了协议的开始标志结束while循环
// if (buffer.getUnsignedByte(beginReader) == HEAD_DATA) {
// // log.info("读到了协议的开始标志结束while循环 byte:{}, HEAD_DATA:{}", buffer.getUnsignedByte(beginReader), HEAD_DATA);
// break;
// }
//
// // 未读到包头,略过一个字节
// // 每次略过,一个字节,去读取,包头信息的开始标记
// buffer.resetReaderIndex();
// buffer.readByte();
//
// // 当略过,一个字节之后,
// // 数据包的长度,又变得不满足
// // 此时,应该结束。等待后面的数据到达
// if (buffer.readableBytes() < BASE_LENGTH) {
// log.debug("数据包的长度不满足 readableBytes:{}, BASE_LENGTH:{}", buffer.readableBytes(), BASE_LENGTH);
// return;
// }
// }
//
// // 消息的长度
// int length = buffer.getUnsignedByte(beginReader + 1);
// // 判断请求数据包数据是否到齐
// if (buffer.readableBytes() < length + 4) {
// // log.info("请求数据包数据没有到齐,还原读指针 readableBytes:{}, 消息的长度:{}", buffer.readableBytes(), length);
// // 还原读指针
// buffer.readerIndex(beginReader);
// return;
// }
//
// // 读取data数据
// byte[] data = new byte[length + 4];
// buffer.readBytes(data);
// ByteBuf frame = buffer.retainedSlice(beginReader, length + 4);
// buffer.readerIndex(beginReader + length + 4);
// out.add(frame);
// }
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
// 记录包头开始的index
@@ -97,7 +97,12 @@ public class StartAndLengthFieldFrameDecoder extends ByteToMessageDecoder {
buffer.markReaderIndex();
// 读到了协议的开始标志结束while循环
if (buffer.getUnsignedByte(beginReader) == HEAD_DATA) {
// if (buffer.getUnsignedByte(beginReader) == HEAD_DATA) {
// break;
// }
// 读到了协议的开始标志结束while循环
if (isStartOfDnyHeader(buffer, beginReader) || isStartOf68Header(buffer, beginReader)) {
break;
}
@@ -132,6 +137,23 @@ public class StartAndLengthFieldFrameDecoder extends ByteToMessageDecoder {
buffer.resetReaderIndex();
}
private boolean isStartOfDnyHeader(ByteBuf buffer, int beginReader) {
if (buffer.readableBytes() >= HEADER_LENGTH_DNY) {
byte[] headerBytes = new byte[HEADER_LENGTH_DNY];
buffer.getBytes(beginReader, headerBytes, 0, HEADER_LENGTH_DNY);
String header = new String(headerBytes, StandardCharsets.UTF_8);
return "DNY".equals(header);
}
return false;
}
private boolean isStartOf68Header(ByteBuf buffer, int beginReader) {
if (buffer.readableBytes() >= HEADER_LENGTH_68) {
return buffer.getUnsignedByte(beginReader) == 0x68;
}
return false;
}
private void decode68Message(ByteBuf buffer, List<Object> out, int beginReader) {
if (buffer.readableBytes() < HEADER_LENGTH_68 + 1) {
buffer.readerIndex(beginReader);

View File

@@ -0,0 +1,98 @@
package com.jsowell.netty.server;
import com.jsowell.common.constant.Constants;
import com.jsowell.netty.server.yunkuaichong.NettyServerChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
@Slf4j
@Component
public class NettyServerManager implements CommandLineRunner {
@Resource
private NettyServerChannelInitializer nettyServerChannelInitializer;
@Override
public void run(String... args) throws Exception {
startNettyServer(Constants.SOCKET_IP, 9011);
startElectricBikeNettyServer(Constants.SOCKET_IP, 9012);
}
public void startNettyServer(String host, int port) {
new Thread(() -> {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.option(ChannelOption.SO_BACKLOG, 128)
.option(ChannelOption.SO_REUSEADDR, true)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.SO_REUSEADDR, true)
.childHandler(nettyServerChannelInitializer)
.localAddress(new InetSocketAddress(host, port));
ChannelFuture future = bootstrap.bind(port).sync();
if (future.isSuccess()) {
log.info("NettyServer启动成功, 开始监听端口:{}", port);
} else {
log.error("NettyServer启动失败", future.cause());
}
future.channel().closeFuture().sync();
} catch (Exception e) {
log.error("NettyServer.start error", e);
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}).start();
}
public void startElectricBikeNettyServer(String host, int port) {
new Thread(() -> {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.option(ChannelOption.SO_BACKLOG, 128)
.option(ChannelOption.SO_REUSEADDR, true)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.SO_REUSEADDR, true)
.childHandler(nettyServerChannelInitializer)
.localAddress(new InetSocketAddress(host, port));
ChannelFuture future = bootstrap.bind(port).sync();
if (future.isSuccess()) {
log.info("ElectricBikeNettyServer启动成功, 开始监听端口:{}", port);
} else {
log.error("ElectricBikeNettyServer启动失败", future.cause());
}
future.channel().closeFuture().sync();
} catch (Exception e) {
log.error("ElectricBikeNettyServer.start error", e);
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}).start();
}
}

View File

@@ -20,7 +20,7 @@ import java.net.InetSocketAddress;
@Slf4j
@Component
@Order(5)
@Order(7)
public class MqttSever implements CommandLineRunner {
@Override

View File

@@ -16,8 +16,9 @@ import javax.annotation.Resource;
import java.net.InetSocketAddress;
@Slf4j
@Component
@Order(2)
@Deprecated
// @Component
// @Order(3)
public class NettyServer implements CommandLineRunner {
@Resource
private NettyServerChannelInitializer nettyServerChannelInitializer;

View File

@@ -21,7 +21,7 @@ public class NettyServerChannelInitializer extends ChannelInitializer<SocketChan
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
// pipeline.addLast("frameDecoder",new CustomDecoder());
pipeline.addLast("frameDecoder", new StartAndLengthFieldFrameDecoder(0x68));
pipeline.addLast("frameDecoder", new StartAndLengthFieldFrameDecoder());
pipeline.addLast("decoder", new ByteArrayDecoder());
pipeline.addLast("encoder", new ByteArrayDecoder());
//读超时时间设置为10s0表示不监控