2025-07-08 14:01:10 +08:00

56 lines
1.7 KiB
C#

using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Yunda.SOMS.OperationsMainSiteGatewayServer.TcpSocket.Server
{
using static ConstValue;
public class FrameHandler : ByteToMessageDecoder
{
protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
{
// 检查数据是否足够一个开始位和长度字段
if (input.ReadableBytes < 1 + LengthFieldSize)
{
return; // 数据不足,等待更多数据
}
// 标记当前读指针,以便在数据不完整时可以回退
input.MarkReaderIndex();
// 检查是否是开始位
byte start = input.ReadByte();
if (start != StartByte)
{
// 如果不是开始位,跳过该字节,继续寻找开始位
input.ResetReaderIndex();
input.SkipBytes(1);
return;
}
// 读取数据长度
int dataLength = input.ReadInt();
// 检查是否收到了完整的数据体以及结束位
if (input.ReadableBytes < dataLength + 1) // 数据体 + 结束位
{
// 数据不完整,恢复读指针,等待更多数据
input.ResetReaderIndex();
return;
}
// 读取数据体
IByteBuffer frame = input.ReadSlice(dataLength);
// 输出完整的数据包内容
output.Add(frame.Retain());
}
}
}