轻松定义自己的网络通讯协议( 二 )


///
/// 网络端点
public void Connect(IPEndPoint iep)
{
this.m_Client.Connect(iep);
}
private byte[] CreateArgPackage(object obj)
{
IPEndPoint local = new IPEndPoint(IPAddress.Any, this.m_Port);
System.IO.MemoryStream outStream = new System.IO.MemoryStream();
this.Serializer.Serialize(outStream, new ReceiveObjectEventArgs(obj, local));
return outStream.ToArray();
}
///
/// 将对象发送到默认主机 。调用此方法前必须先调用Connect方法连接默认主机 。
///
/// 要发送的对象
public void Send(object obj)
{
if (this.IsConnected)
{
byte[] data = https://www.rkxy.com.cn/dnjc/this.CreateArgPackage(obj);
this.m_Client.Send(data, data.Length);
}
else
{
throw new Exception("必须先连接默认主机");
}
}
///
/// 将对象发送到指定的主机 。若调用了Connect方法连接了默认主机,则此方法不可用 。
///
/// 要发送的对象
/// 目标主机的网络端点
public void Send(object obj, IPEndPoint remoteIEP)
{
if (this.IsConnected)
{
throw new Exception("已经连接了默认主机");
}
else
{
byte[] data = https://www.rkxy.com.cn/dnjc/this.CreateArgPackage(obj);
this.m_Client.Send(data, data.Length, remoteIEP);
}
}
///
/// 监听接收数据线程方法
///
protected void Listen()
{
BinaryFormatter Serializer = new BinaryFormatter();
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
object revobj = Serializer.Deserialize(new System.IO.MemoryStream(m_Client.Receive(ref RemoteIpEndPoint)));
ReceiveObjectEventArgs revarg = (ReceiveObjectEventArgs)revobj;
RemoteIpEndPoint.Port = revarg.RemoteIEP.Port;
revarg.RemoteIEP = RemoteIpEndPoint;
if (this.ReceiveObject != null)
{
this.ReceiveObject(this, revarg);
}
}
catch
{
break;
}
}
}
#region 公共属性区
///
/// 返回或设置接收对象的端口号
///
public int Port
{
get
{
return this.m_Port;
}
set
{
this.m_Port = value;
}
}
///
/// 返回对象发送器是否已经初始化并开始工作
///
public bool IsStart
{
get
{
return this.m_IsStart;
}
}
///
/// 返回对象发送器是否已经连接默认远程主机
///
public bool IsConnected
{
get
{
return this.m_IsConnected;
}
}
#endregion
#region IDisposable 成员
public void Dispose()
{
// TODO: 添加 ObjectTransferClient.Dispose 实现
this.m_Client.Close();
this.ListenThread.Abort();
}
#endregion
}
///
/// 接收对象事件参数
///
[Serializable]
public class ReceiveObjectEventArgs : EventArgs
{
private object _obj;
private System.Net.IPEndPoint _iep;
///
/// 构建一个接收对象事件的参数
///
/// 接收到的对象
/// 【轻松定义自己的网络通讯协议】发送者的网络端点
internal ReceiveObjectEventArgs(object obj, System.Net.IPEndPoint iep)
{
this._obj = obj;
this._iep = iep;
}
///
/// 构建一个空的接收对象事件参数
///
public ReceiveObjectEventArgs():this(null, null)
{
}
///
/// 接收到的对象
///
public object Obj
{
get
{
return this._obj;
}
}
///
/// 发送方的网络端点

推荐阅读