程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> TCP發消息續傳文件,tcp消息續傳

TCP發消息續傳文件,tcp消息續傳

編輯:C#入門知識

TCP發消息續傳文件,tcp消息續傳


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;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved