网络通信
public class NetClient
{
///
/// 接收数据缓冲区大小64K
///
public const int DefaultBufferSize = 64 * 1024;
public event EventHandler OnConnectionChanged;
public event EventHandler OnSocketEventRaised;
public event EventHandler OnSocketErrorRaised;
#region 字段
///
/// 客户端与服务器之间的会话类
///
private Session _session;
///
/// 客户端是否已经连接服务器
///
private bool _isConnected = false;
///
/// 报文解析器
///
private DatagramResolver _resolver;
///
/// 通讯格式编码解码器
///
private Coder _coder;
///
/// 接收数据缓冲区
///
private byte[] _recvDataBuffer = new byte[DefaultBufferSize];
#endregion
#region 事件定义
///
/// 已经连接服务器事件
///
public event NetEvent ConnectedServer;
///
/// 接收到数据报文事件
///
public event NetEvent ReceivedDatagram;
///
/// 连接断开事件
///
public event NetEvent DisConnectedServer;
#endregion
#region 属性
///
/// 返回客户端与服务器之间的会话对象
///
public Session ClientSession
{
get
{
return _session;
}
}
///
/// 返回客户端与服务器之间的连接状态
///
public bool IsConnected
{
get
{
return _isConnected;
}
}
///
/// 数据报文分析器
///
public DatagramResolver Resovlver
{
get
{
return _resolver;
}
set
{
_resolver = value;
}
}
///
/// 编码解码器
///
public Coder ServerCoder
{
get
{
return _coder;
}
}
#endregion
#region 公有方法
///
/// 默认构造函数,使用默认的编码格式
///
public NetClient()
{
_coder = new Coder(Coder.EncodingMothord.Default);
}
///
/// 构造函数,使用一个特定的编码器来初始化
///
/// 报文编码器
public NetClient(Coder coder)
{
_coder = coder;
}
///
/// 连接服务器
///
/// 服务器IP地址
/// 服务器端口
public virtual void Connect(string ip, int port)
{
/*
if (IsConnected)
{
Debug.Assert(_session != null);
Close();
}
*/
Socket newClientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ip), port);
newClientSocket.BeginConnect(iep, new AsyncCallback(Connected), newClientSocket);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public virtual void Disconnect()
{
}
///
/// 发送数据报文
///
///
public virtual void Send(string datagram)
{
if (datagram.Length == 0)
{
return;
}
if (!_isConnected)
{
throw (new ApplicationException("没有连接服务器,不能发送数据"));
}
//获得报文的编码字节
byte[] data = _coder.GetEncodingBytes(datagram);
_session.ClientSocket.BeginSend(data, 0, data.Length, SocketFlags.None,
new AsyncCallback(SendDataEnd), _session.ClientSocket);
}
///
/// 发送数据报文
///
///
public virtual void SendBytes(byte[] dataBytes)
{
if (dataBytes.Length == 0)
{
return;
}
if (!_isConnected)
{
throw (new ApplicationException("没有连接服务器,不能发送数据"));
}
//获得报文的编码字节
byte[] data = _coder.GetEncodingBytes(dataBytes, _resolver);
_session.ClientSocket.BeginSend(data, 0, data.Length, SocketFlags.None,
new AsyncCallback(SendDataEnd), _session.ClientSocket);
}
#endregion
#region 受保护方法
///
/// 数据发送完成处理函数
///
///
protected virtual void SendDataEnd(IAsyncResult iar)
{
Socket remoteSocket = (Socket)iar.AsyncState;
int sent = remoteSocket.EndSend(iar);
//Debug.Assert(sent != 0);
}
///
/// 建立Tcp连接后处理过程
///
/// 异步Socket
protected virtual void Connected(IAsyncResult iar)
{
Socket cliectSocket = (Socket)iar.AsyncState;
try
{
cliectSocket.EndConnect(iar);
//创建新的会话
_session = new Session(cliectSocket);
_isConnected = true;
SetConnection(_isConnected);
//触发连接建立事件
if (ConnectedServer != null)
{
ConnectedServer(this, new NetEventArgs(_session));
}
_session.ClientSocket.BeginReceive(_recvDataBuffer, 0,
DefaultBufferSize, SocketFlags.None,
new AsyncCallback(ReceiveData), cliectSocket);
Mark(string.Format("连接成功"));
}
catch
{
//throw new Exception(ex.Message);
//_isConnected = false;
WriteLog(sex, sex.ErrorCode.ToString());
//SetConnection(_isConnected);
}
}
///
/// 关闭连接
///
public virtual void Close()
{
if (!_isConnected)
{
return;
}
_session.Close();
_session = null;
_isConnected = false;
}
public virtual void SetConnection(bool IsConnected)
{
//if (!IsConnected && cliectSocket != null)
//{
// state.IsReceiveThreadAlive = false;
// try
// {
// if (statelst.Contains(state))
// statelst.Remove(state);
// state.workSocket.Shutdown(SocketShutdown.Both);
// state.workSocket.Close();
// }
// catch (Exception Ex)
// {
// //WriteLog(Ex, "When release socket connection.");
// }
//}
if (OnConnectionChanged != null)
OnConnectionChanged(this, new EventArgCollection.ConnectionEventArgs() { IsConnected = IsConnected });
}
public void Mark(string s)
{
var Id = System.Threading.Thread.CurrentThread.ManagedThreadId;
if (OnSocketEventRaised != null)
OnSocketEventRaised(null, new EventArgCollection.SocketEventArgs() { Msg = string.Format("[线程ID:{0}] {1}", Id, s) });
}
public void WriteLog(Exception exp, string msg)
{
if (OnSocketErrorRaised != null)
OnSocketErrorRaised(exp.Message, new EventArgCollection.SocketErrorEventArgs() { Exp = exp, Msg = msg });
}
///
/// 数据接收处理函数
///
/// 异步Socket
protected virtual void ReceiveData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
try
{
int recv = remote.EndReceive(iar);
if (recv == 0)
{
_session.TypeOfExit = Session.ExitType.NormalExit;
if (DisConnectedServer != null)
{
DisConnectedServer(this, new NetEventArgs(_session));
}
return;
}
byte[] receiveDataBytes = _coder.GetDecodingBytes(_recvDataBuffer, recv);
//ConcurrentDictionary dic = new ConcurrentDictionary();
//string receivedData = _coder.GetEncodingString(_recvDataBuffer, recv);
//通过事件发布收到的报文
if (ReceivedDatagram != null)
{
ICloneable copySession = (ICloneable)_session;
Session clientSession = (Session)copySession.Clone();
clientSession.RecvDataBuffer = new byte[receiveDataBytes.Length];
Array.ConstrainedCopy(receiveDataBytes, 0, clientSession.RecvDataBuffer, 0, receiveDataBytes.Length);
//clientSession.Datagram = newDatagram;
//发布一个报文消息
ReceivedDatagram(this, new NetEventArgs(clientSession));
if (_resolver != null)
{
//if (_session.Datagram != null && _session.Datagram.Length != 0)
//{
// receivedData = _session.Datagram + receivedData;
//}
//string[] recvDatagrams = _resolver.Resolve(ref receivedData);
//foreach (string newDatagram in recvDatagrams)
//{
// ICloneable copySession = (ICloneable)_session;
// Session clientSession = (Session)copySession.Clone();
// clientSession.Datagram = newDatagram;
// //发布一个报文消息
// ReceivedDatagram(this, new NetEventArgs(clientSession));
//}
剩余的代码片断,下次接收的时候使用
//_session.Datagram = receivedData;
}
else
{
//ICloneable copySession = (ICloneable)_session;
//Session clientSession = (Session)copySession.Clone();
//clientSession.Datagram = receivedData;
//ReceivedDatagram(this, new NetEventArgs(clientSession));
}
}//end of if(ReceivedDatagram != null)
//继续接收数据
_session.ClientSocket.BeginReceive(_recvDataBuffer, 0, DefaultBufferSize, SocketFlags.None,
new AsyncCallback(ReceiveData), _session.ClientSocket);
}
catch (SocketException ex)
{
//主机端退出
if (10054 == ex.ErrorCode)
{
_session.TypeOfExit = Session.ExitType.ExceptionExit;
if (DisConnectedServer != null)
{
DisConnectedServer(this, new NetEventArgs(_session));
}
//_isConnected = false;
//WriteLog(ex, ex.ErrorCode.ToString());
}
else
{
//throw (ex);
}
}
catch (ObjectDisposedException ex)
{
if (ex != null)
{
ex = null;
//DoNothing;
}
//_isConnected = false;
}
}
#endregion
}
事件参数设定
public class EventArgCollection
{
///
/// ConnectionEventArgs
///
public class ConnectionEventArgs : EventArgs
{
public bool IsConnected { get; set; }
}
///
/// SocketEventArgs
///
public class SocketEventArgs : EventArgs
{
///
/// ClientName
///
public string ClientName { get; set; }
///
/// IsConnect
///
public bool IsConnect { get; set; }
///
/// Message
///
public string Msg { get; set; }
}
///
/// ErrorEventArgs
///
public class SocketErrorEventArgs : EventArgs
{
///
/// Exception
///
public Exception Exp { get; set; }
///
/// Message
///
public string Msg { get; set; }
}
}
///
/// 网络通讯事件模型委托
///
public delegate void NetEvent(object sender, NetEventArgs e);
连接处理通用
public class Transmitter_Network
{
public byte[] m_HeadBytes = new byte[4] { 0xfa, 0xfb, 0xfc, 0xfd }; //字头信息
#region ** 内部私有变量 **
NetClient m_NetClient;
private bool _isConnected = false;
#endregion
#region ** 构造函数 **
public Transmitter_Network()
{
_ThreadIsWork = true;
_ThreadIsPause = false;
CreateWorkThread();
_ThreadIsWork_Send = true;
_ThreadIsPause_Send = false;
CreateWorkThread_Send();
NetInitializeComponent();
}
#endregion
#region ** 数据传输 **
private void NetInitializeComponent()
{
m_NetClient = new NetClient(new Coder(Coder.EncodingMothord.Default));
//m_NetClient.Resovlver=new DatagramResolver("]}");
m_NetClient.Resovlver = new DatagramResolver(m_HeadBytes);
m_NetClient.ReceivedDatagram += M_NetClient_ReceivedDatagram;
m_NetClient.DisConnectedServer += M_NetClient_DisConnectedServer;
m_NetClient.ConnectedServer += M_NetClient_ConnectedServer;
m_NetClient.OnSocketErrorRaised += M_NetClient_OnSocketErrorRaised;
m_NetClient.OnSocketEventRaised += M_NetClient_OnSocketEventRaised;
//m_NetClient.Connect("192.168.1.166", 6500);
//m_NetClient.Connect("10.10.100.254", 8899);
}
//public event EventHandler OnConnectionChanged;
public event EventHandler OnSocketEventRaised;
public event EventHandler OnSocketErrorRaised;
private void M_NetClient_OnSocketEventRaised(object sender, EventArgCollection.SocketEventArgs e)
{
//throw new NotImplementedException();
if (OnSocketEventRaised != null)
OnSocketEventRaised(null, new EventArgCollection.SocketEventArgs() { Msg = string.Format("[线程ID:{0}] {1}", "", e.Msg) });
}
private void M_NetClient_OnSocketErrorRaised(object sender, EventArgCollection.SocketErrorEventArgs e)
{
//throw new NotImplementedException();
if (OnSocketErrorRaised != null)
OnSocketErrorRaised(e.Exp.Message, new EventArgCollection.SocketErrorEventArgs() { Exp = e.Exp, Msg = e.Msg });
}
private void M_NetClient_ConnectedServer(object sender, NetEventArgs e)
{
//throw new NotImplementedException();
string info = string.Format("A Client:{0} connect server :{1}", e.ClientSession,
e.ClientSession.ClientSocket.RemoteEndPoint.ToString());
}
private void M_NetClient_DisConnectedServer(object sender, NetEventArgs e)
{
//throw new NotImplementedException();
string info;
if (e.ClientSession.TypeOfExit == Session.ExitType.ExceptionExit)
{
info = string.Format("A Client Session:{0} Exception Closed.",
e.ClientSession.ID);
}
else
{
info = string.Format("A Client Session:{0} Normal Closed.",
e.ClientSession.ID);
}
}
DateTime time_Main0 = DateTime.Now;
TimeSpan timeSpan_Main = new TimeSpan(0, 0, 0, 0);
int RDataCount = 0;
public delegate void RuntimeUpdateEventDelegate(TimeSpan TimeSpan, int RDataCount, int WDataCount);
public event RuntimeUpdateEventDelegate RuntimeUpdate;
public delegate void MyReceiveDataEventDelegate(byte[] dataBytes);
public event MyReceiveDataEventDelegate MyReceiveData;
public delegate void MyReceiveCommandEventDelegate(byte[] dataBytes);
public event MyReceiveCommandEventDelegate MyReceiveCommand;
public delegate void MySendDataEventDelegate(byte[] dataBytes);
public event MySendDataEventDelegate MySendData;
private void M_NetClient_ReceivedDatagram(object sender, NetEventArgs e)
{
//throw new NotImplementedException();
int DataByteLength = e.ClientSession.RecvDataBuffer.Length;
byte[] ReceiveDataBytes = new byte[DataByteLength];
Array.ConstrainedCopy(e.ClientSession.RecvDataBuffer, 0, ReceiveDataBytes, 0, DataByteLength);
if (MyReceiveData != null)
MyReceiveData(ReceiveDataBytes);
WdataCount = RDataCount - WdataCount;
RDataCount = Split_ReceiveDataBytes(ReceiveDataBytes);
DateTime time_Main1 = DateTime.Now;
timeSpan_Main = time_Main1.Subtract(time_Main0);
time_Main0 = time_Main1;
if (RuntimeUpdate != null)
RuntimeUpdate(timeSpan_Main, RDataCount, WdataCount);
}
object obj = new object();
private int Split_ReceiveDataBytes(byte[] ReceiveDataBytes)
{
int dataCount = 0;
for (int i = 0; i < ReceiveDataBytes.Length; i++)
{
if (i + 4 < ReceiveDataBytes.Length)
{
if (ReceiveDataBytes[i] == m_HeadBytes[0] && ReceiveDataBytes[i + 1] == m_HeadBytes[1] && ReceiveDataBytes[i + 2] == m_HeadBytes[2] && ReceiveDataBytes[i + 3] == m_HeadBytes[3])
{
//找到
int dataLength = Coder.ByteToInt32(ReceiveDataBytes[i + 4]);
byte[] dataBytes = new byte[dataLength];
if (i + 5 + dataLength - 1 < ReceiveDataBytes.Length)
{
Array.ConstrainedCopy(ReceiveDataBytes, i + 5, dataBytes, 0, dataLength);
lock (this)
{
if (CheckDigitByte(dataBytes))
{
//校验检测OK
if (dataBytes[0] == 0x25 && dataBytes[1] == 0x01 && dataBytes[2] == 0x02)
{
try
{
receive_Q.Enqueue(dataBytes);
}
catch
{
}
}
else
{
if (MyReceiveCommand != null)
MyReceiveCommand(dataBytes);
}
}
}
//ResolveReceiveData(dataBytes);
i = i + 5 + dataLength - 1;
dataCount++;
}
}
}
}
return dataCount;
}
///
/// 校验检测
///
///
///
public bool CheckDigitByte(byte[] dataBytes)
{
if (dataBytes.Length < 2) return false;
byte CheckDigitByte = dataBytes[dataBytes.Length - 1];
byte dataByte = new byte();
for (int i = 0; i < dataBytes.Length - 1; i++)
{
dataByte += dataBytes[i];
}
return dataByte == CheckDigitByte;
}
#endregion
#region ** 属性 **
public bool IsConnected
{
get
{
this._isConnected = m_NetClient.IsConnected;
return this._isConnected;
}
}
public object Dispatcher { get; private set; }
#endregion
#region ** 公共方法 **
///
/// 模拟人连接
///
public void NetworkConnect()
{
try
{
NetworkConnect("127.0.0.1", 8899);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 模拟人连接
///
///
///
public void NetworkConnect(string IP, int Port)
{
try
{
m_NetClient.Connect(IP, Port);
Thread.Sleep(100); //等1秒
this._isConnected = m_NetClient.IsConnected;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 网络连接断开
///
public void NetworkDisconnect()
{
try
{
m_NetClient.Disconnect();
Thread.Sleep(100); //等1秒
this._isConnected = m_NetClient.IsConnected;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public void AddSendBytes(byte[] dataBytes)
{
try
{
//Cache_SendDataBytes.Add(dataBytes);
//入队
System.Diagnostics.Debug.WriteLine(string.Format("{0},{1}", Common.Converter.ByteConverter.ByteArrayToHexString(dataBytes), send_Q.Count));
send_Q.Enqueue(dataBytes);
}
catch (Exception)
{
//throw;
}
}
///
/// 发送数据到模拟人
///
///
private void SendBytes(byte[] dataBytes)
{
try
{
m_NetClient.SendBytes(dataBytes);
if (MySendData != null)
MySendData(dataBytes);
}
catch
{
//MessageBox.Show(ex.Message, "错误");
}
}
#endregion
#region ** 读取队列数据作业线程 **
//private List Cache_ReceiveDataBytes = new List();
Queue receive_Q = new Queue();
Thread WorkThread;
AutoResetEvent WorkResetEvent = new AutoResetEvent(true);
private bool _ThreadIsWork = false;
private bool _ThreadIsPause = false;
///
/// 创建前线程
///
public void CreateWorkThread()
{
this.WorkThread = new Thread(new ThreadStart(this.WorkThreedFun));
this.WorkThread.IsBackground = true;
this.WorkThread.Start();
}
///
///
///
public void DestroyWorkThread()
{
_ThreadIsWork = false;
Thread.Sleep(100);
WorkThread.DisableComObjectEagerCleanup();
}
///
/// 执行线程函数
///
private void WorkThreedFun()
{
while (true)
{
if (!_ThreadIsWork || _ThreadIsPause)
{
this.WorkResetEvent.WaitOne();
}
this.DoWork();
}
}
//int workRunTime = 0;
DateTime time_Main20 = DateTime.Now;
TimeSpan timeSpan_Main2 = new TimeSpan(0, 0, 0, 0);
public delegate void RuntimeUpdate2EventDelegate(TimeSpan TimeSpan, int DataCount);
//public event RuntimeUpdate2EventDelegate RuntimeUpdate2;
int WdataCount = 0;
///
/// 取出数据
///
private void DoWork()
{
while (receive_Q.Count > 0)
{
//出队
byte[] dataBytes = (byte[])receive_Q.Dequeue();
if (dataBytes != null)
{
//发送数据
//SendBytes(dataBytes);
if (MyReceiveCommand != null)
MyReceiveCommand(dataBytes);
}
//小于20条快速取出
if (receive_Q.Count < 20)
System.Threading.Thread.Sleep(10);
};
}
private byte[] ReadCacheData()
{
byte[] dataBytes = new byte[0];
//if (Cache_ReceiveDataBytes.Count >= 10)
//{
// dataBytes = Cache_ReceiveDataBytes[0];
// Cache_ReceiveDataBytes.RemoveAt(0);
//}
return dataBytes;
}
///
/// 查找是否存在的字节数据
///
///
///
///
private bool InByte(byte[] byteDataArray, byte byteData)
{
if (byteDataArray == null)
return false;
for (int i = 0; i < byteDataArray.Length; i++)
{
if (byteDataArray[i] == byteData)
{
return true;
}
}
return false;
}
#endregion
#region ** 发送队列数据作业线程 **
Queue send_Q = new Queue();
Thread WorkThread_Send;
AutoResetEvent WorkResetEvent_Send = new AutoResetEvent(true);
private bool _ThreadIsWork_Send = false;
private bool _ThreadIsPause_Send = false;
///
/// 创建前线程
///
public void CreateWorkThread_Send()
{
this.WorkThread_Send = new Thread(new ThreadStart(this.WorkThreedFun_Send));
this.WorkThread_Send.IsBackground = true;
this.WorkThread_Send.Start();
}
///
///
///
public void DestroyWorkThread_Send()
{
_ThreadIsWork_Send = false;
Thread.Sleep(100);
WorkThread_Send.DisableComObjectEagerCleanup();
}
///
/// 执行线程函数
///
private void WorkThreedFun_Send()
{
while (true)
{
if (!_ThreadIsWork_Send || _ThreadIsPause_Send)
{
this.WorkResetEvent_Send.WaitOne();
}
this.DoWork_Send();
}
}
//int workRunTime_Send = 0;
DateTime time_Main20_Send = DateTime.Now;
TimeSpan timeSpan_Main2_Send = new TimeSpan(0, 0, 0, 0);
public delegate void RuntimeUpdate2_SendEventDelegate(TimeSpan TimeSpan, int DataCount);
//public event RuntimeUpdate2_SendEventDelegate RuntimeUpdate2_Send;
//int WdataCount_Send = 0;
///
/// 取出数据
///
private void DoWork_Send()
{
while (send_Q.Count > 0)
{
//出队
System.Diagnostics.Debug.WriteLine(string.Format("{0}", send_Q.Count));
byte[] dataBytes = (byte[])send_Q.Dequeue();
System.Diagnostics.Debug.WriteLine(string.Format("{0}", Common.Converter.ByteConverter.ByteArrayToHexString(dataBytes)));
if (dataBytes != null)
{
//发送数据
SendBytes(dataBytes);
}
System.Threading.Thread.Sleep(10);
};
}
private byte[] ReadCacheData_Send()
{
byte[] dataBytes = new byte[0];
//if (Cache_ReceiveDataBytes.Count >= 10)
//{
// dataBytes = Cache_ReceiveDataBytes[0];
// Cache_ReceiveDataBytes.RemoveAt(0);
//}
return dataBytes;
}
#endregion
#region ** 私有方法 **
#endregion
}
调用
Transmitter_Network Transmitter_Network = new Transmitter_Network();
Transmitter_Network.NetworkConnect(Ip, Port);
if(Transmitter_Network.IsConnected)
{
//成功
}
else
{
//失败
}