您的位置:首页 > 理论基础 > 计算机网络

.Net网络通讯编程[利用Socket实现字串、文件、序列化对象传输]--类设计1

2012-03-28 09:00 1111 查看
本案例使用.Net Socket的Tcp、Udp实现字串、文件、各种序列化对象的网络传输,同时封装了Tcp的粘包、半包处理细节,定义了网络封包格式,在发送端和接收端无需考虑内部传输细节。以下是类设计:

序列化相关类类图:

示范代码using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TcpLabCommon
{
/// <summary>
/// 包类型
/// </summary>
public enum PacketType
{
/// <summary>
/// 简单字符串传输
/// </summary>
STRING=0,
/// <summary>
/// 二进制[文件传输]
/// </summary>
BINARY=1,
/// <summary>
/// 复杂对象传输[使用序列化和反序列化]
/// </summary>
COMPLEX=2
}

/// <summary>
/// 包头
/// </summary>
public class NetPacketHead
{
/// <summary>
/// 包头大小
/// </summary>
public const Int32 HEAD_SIZE = 4 * 3;

private Int32 _version = 1;

/// <summary>
/// 版本
/// </summary>
public Int32 Version
{
get { return _version; }
set { _version = value; }
}

private PacketType _pType = PacketType.STRING;
/// <summary>
/// 包类型[决定如何解包]
/// </summary>
public PacketType PType
{
get { return _pType; }
set { _pType = value; }
}

private Int32 _len = 0;
/// <summary>
/// 包体长度[决定后面data数据的长度]
/// </summary>
public Int32 Len
{
get { return _len; }
set { _len = value; }
}

}

/// <summary>
/// 网络数据包【Udp建议大小不超过548个字节,Internet标准MTU为576,减去IP数据报头(20字节)和UDP数据包头(8字节)】
/// </summary>
public class NetPacket
{

NetPacketHead _packetHead;
/// <summary>
/// 包头
/// </summary>
public NetPacketHead PacketHead
{
get { return _packetHead; }
set { _packetHead = value; }
}

private object _data=null;
/// <summary>
/// 包体,根据封包类型决定包体数据类型
/// STRING:包体为String
/// BINARY:包体为Byte[]
/// COMPLEX:包体为可序列化的对象
/// </summary>
public object Data
{
get { return _data; }
set { _data = value; }
}
}

/// <summary>
/// 传输的文件
/// </summary>
public class NetFile
{
private string _fileName = string.Empty;

public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
private Byte[] _content;

public Byte[] Content
{
get
{
if (_content==null)
_content = new Byte[]{};
return _content;
}
set { _content = value; }
}
}
}


提供网络封包传输服务的核心类:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐