/// <summary>
/// 编码
/// </summary>
public override void Encode(ByteBuffer sendBuffer, System.Object packageObj)
{
DefaultNetworkPackage package = (DefaultNetworkPackage)packageObj;
if (package == null)
{
HandleError(false, $"The package object is invalid : {packageObj.GetType()}");
return;
}
// 检测逻辑是否合法
if (package.IsHotfixPackage)
{
if (package.BodyBytes == null)
{
HandleError(false, $"The package BodyBytes field is null : {packageObj.GetType()}");
return;
}
}
else
{
if (package.MsgObj == null)
{
HandleError(false, $"The package MsgObj field is null : {packageObj.GetType()}");
return;
}
}
// 获取包体数据
byte[] bodyData;
if (package.IsHotfixPackage)
{
bodyData = package.BodyBytes;
}
else
{
bodyData = EncodeInternal(package.MsgObj);
}
// 检测包体长度
if (bodyData.Length > PackageBodyMaxSize)
{
HandleError(false, $"The package {package.MsgID} body size is larger than NetworkDefine.PackageBodyMaxSize");
return;
}
// 写入长度
int packetSize = (int)MessageIDFieldType + bodyData.Length;
if (PackageSizeFieldType == EPackageSizeFieldType.UShort)
{
// 检测是否越界
if (packetSize > ushort.MaxValue)
{
HandleError(true, $"The package {package.MsgID} size is larger than ushort.MaxValue.");
return;
}
sendBuffer.WriteUShort((ushort)packetSize);
}
else
{
sendBuffer.WriteInt(packetSize);
}
// 写入包头
{
// 写入消息ID
if (MessageIDFieldType == EMessageIDFieldType.UShort)
{
// 检测是否越界
if (package.MsgID > ushort.MaxValue)
{
HandleError(true, $"The package {package.MsgID} ID is larger than ushort.MaxValue");
return;
}
sendBuffer.WriteUShort((ushort)package.MsgID);
}
else
{
sendBuffer.WriteInt(package.MsgID);
}
}
// 写入包体
sendBuffer.WriteBytes(bodyData, 0, bodyData.Length);
}