码迷,mamicode.com
首页 > 其他好文 > 详细

TCP发消息续传文件

时间:2016-08-01 11:56:20      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

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

 

TCP发消息续传文件

标签:

原文地址:http://www.cnblogs.com/Logan626/p/5724842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!