1.自定義固定協議頭部。格式:([head][body][filestream])
/// <summary>
/// 數據包頭部
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct ZsyDataPackHead
{
/// <summary>
/// 客戶端ID
/// </summary>
public int ClientID;
/// <summary>
/// 客戶端類型
/// </summary>
public int ClientType;
/// <summary>
/// 命令值
/// </summary>
public int CommandVal;
/// <summary>
/// 擴展類型
/// </summary>
public int ExtendType;
/// <summary>
/// 用戶ID
/// </summary>
public int UserID;
/// <summary>
/// 會話ID
/// </summary>
public int CookeID;
/// <summary>
/// 內容大小
/// </summary>
public int BodySize;
/// <summary>
/// 擴展數據大小
/// </summary>
public int ExtendSize;
}
2.發送消息
private void SendMsg(ZsyDataPackHead head, byte[] bodyInfo, byte[] bdatas = null)
{
int extendlen = 0;
if (bodyInfo == null)
return;
if (bdatas != null)
extendlen = bdatas.Length;
int totalsize = Utility.HeadSize + bodyInfo.Length + extendlen;
byte[] senddata = new byte[totalsize];
byte[] headbyte = Utility.Struct2Bytes<ZsyDataPackHead>(head);
senddata.InsertArray<byte>(0, headbyte);
senddata.InsertArray<byte>(Utility.HeadSize, bodyInfo);
if (bdatas != null)
senddata.InsertArray<byte>(Utility.HeadSize + bodyInfo.Length, bdatas);
if (!client.TrySend(new ArraySegment<byte>(senddata)))
AddItem("發送失敗");
if (client.ReceiveBufferSize < totalsize)
AddItem("數據包太大");
}
3.組包
List<byte[]> lst = new List<byte[]>();
List<ServiceData> lstdata = new List<ServiceData>();
while (fs2.Position < fs2.Length)
{
int zsyfilesteamsize = int.Parse(ConfigurationManager.AppSettings["packsize"]) - int.Parse(ConfigurationManager.AppSettings["bodysize"]);
data = new byte[zsyfilesteamsize];//文件流數據包字節數組
int count = fs2.Read(data, 0, data.Length);
if (count != data.Length)
data = data.SubArray<byte>(0, count);
lst.Add(data);
data = null;
}
4.服務器端解包
using (FileStream fs = new FileStream(filepath, FileMode.Append))
{
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(zsy.ExtendData);
bw.Close();
fs.Close();
zsy.ExtendData = null;
}