/// <summary> /// 侦听到客户端数据回调his the call back function which will be invoked when the socket /// detects any client writing of data on the stream /// </summary> /// <param name="asyn"></param> private void ReadCallBack(IAsyncResult asyn) { SocketPacket socketData = (SocketPacket)asyn.AsyncState; try { // Complete the BeginReceive() asynchronous call by EndReceive() method // which will return the number of characters written to the stream // by the client int iRx = socketData.m_currentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; // Extract the characters as a buffer System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); // 构造事件 ItemValueResult[] values = new ItemValueResult[1]; values[0] = new ItemValueResult(); values[0].Value = socketData.dataBuffer; values[0].ItemName = "MODBUS Server:" + socketData.m_currentSocket.LocalEndPoint.ToString(); base.OnDataChange(null, null, values); // Send back the reply to the client string replyMsg = "Server Reply:" + szData.ToUpper(); // Convert the reply to byte array byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg); Socket workerSocket = (Socket)socketData.m_currentSocket; workerSocket.Send(byData); // Continue the waiting for data on the Socket WaitForData(socketData.m_currentSocket, socketData.m_clientNumber); } catch (ObjectDisposedException ex) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); CLOGException.Trace("函数CommunicationLib.CTcpServerAccess.ReadCallBack 异常", CBaseMethods.MyBase.GetExceptionInfo(ex)); } catch (SocketException ex) { if (ex.ErrorCode == 10054) // Error code for Connection reset by peer { // Remove the reference to the worker socket of the closed client // so that this object will get garbage collected m_workerSocketList[socketData.m_clientNumber - 1] = null; } CLOGException.Trace("函数CommunicationLib.CTcpServerAccess.ReadCallBack 异常", CBaseMethods.MyBase.GetExceptionInfo(ex)); } }
/// <summary> /// 开始等待客户端数据Start waiting for data from the client /// </summary> /// <param name="soc"></param> /// <param name="clientNumber"></param> private void WaitForData(System.Net.Sockets.Socket soc, int clientNumber) { try { if (pfnWorkerCallBack == null) { // Specify the call back function which is to be // invoked when there is any write activity by the // connected client pfnWorkerCallBack = new AsyncCallback(ReadCallBack); } SocketPacket theSocPkt = new SocketPacket(soc, clientNumber); soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt); } catch (SocketException ex) { CLOGException.Trace("函数CommunicationLib.CTcpServerAccess.WaitForData 异常", CBaseMethods.MyBase.GetExceptionInfo(ex)); } }