标签:
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;
}
标签:
原文地址:http://www.cnblogs.com/Logan626/p/5724842.html