update 电单车协议

This commit is contained in:
Guoqs
2024-08-03 16:09:02 +08:00
parent b535eba509
commit 01770b2123
5 changed files with 9 additions and 8 deletions

View File

@@ -0,0 +1,47 @@
package com.jsowell.netty.decoder;
import com.jsowell.common.protocol.Message;
import com.jsowell.common.protocol.MessageConstant;
import com.jsowell.common.util.bean.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
public class MessageDecode extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
// 由于数据包的前4个字节用于记录总数据大小如果数据不够4个字节不进行读
if(byteBuf.readableBytes() < 4) {
return;
}
// 标记开始读的位置
byteBuf.markReaderIndex();
// 前四个字节记录了数据大小
int dataSize = byteBuf.readInt();
// 查看剩余可读字节是否足够,如果不是,重置读取位置,等待下一次解析
if(byteBuf.readableBytes() < dataSize) {
byteBuf.resetReaderIndex();
return;
}
// 读取消息类型
byte messageType = byteBuf.readByte();
// 读取数据, 数组大小需要剔除1个字节的消息类型
byte[] data = new byte[dataSize -1];
byteBuf.readBytes(data);
Message message = SerializationUtil.deserialize(MessageConstant.getMessageClass(messageType), data);
list.add(message);
}
}

View File

@@ -0,0 +1,24 @@
package com.jsowell.netty.decoder;
import com.jsowell.common.protocol.Message;
import com.jsowell.common.util.bean.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public class MessageEncode extends MessageToByteEncoder<Message> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
// 将对象进行序列化
byte[] data = SerializationUtil.serialize(message);
// 写数据长度前4个字节用于记录数据总长度对象 + 类型1个字节
byteBuf.writeInt(data.length + 1);
// 写记录消息类型,用于反序列选择类的类型
byteBuf.writeByte(message.getMessageType());
// 写对象
byteBuf.writeBytes(data);
}
}

View File

@@ -1,6 +1,7 @@
package com.jsowell.netty.server.electricbicycles;
import com.jsowell.netty.decoder.ChargingPileDecoder;
import com.jsowell.netty.decoder.MessageDecode;
import com.jsowell.netty.decoder.StartAndLengthFieldFrameDecoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
@@ -25,8 +26,8 @@ public class ElectricBicyclesServerChannelInitializer extends ChannelInitializer
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast("frameDecoder", new StartAndLengthFieldFrameDecoder());
pipeline.addLast("decoder", new ByteArrayDecoder());
pipeline.addLast("encoder", new ByteArrayDecoder());
pipeline.addLast("decoder", new MessageDecode());
pipeline.addLast("encoder", new MessageDecode());
//读超时时间设置为10s0表示不监控
pipeline.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
pipeline.addLast("handler", chargingPileHandler);