/** * */ private void ReceiveMsgCallback(IAsyncResult receiveRes) { if (!IsConnected()) { ClientLog.LogError("ReceiveMsgCallback : the socket is not connected!!!"); return; } MsgReceiveHelper receiveHelper = null; try { int _recSize = this._socketClient.EndReceive(receiveRes); if (_recSize > 0) { receiveHelper = (MsgReceiveHelper)receiveRes.AsyncState; this.DecodeMsg(receiveHelper.buffer, _recSize); } // < 0, the remote socket is close... else { SetShowNetworkError(1, 0, SocketError.SocketError); ClientLog.LogError("Socket EndReceive failed, the size is 0. The remote socket is closed. Disconnect..."); this.Close(); return; } } // catch (SocketException se) { SetShowNetworkError(2, se.ErrorCode, se.SocketErrorCode); ClientLog.LogError("receive msg failed : " + se.ToString()); ClientLog.LogError("Socket EndReceive Exception, ErrorCode = " + se.ErrorCode.ToString() + ", SocketErrorCode = " + se.SocketErrorCode.ToString()); // Disconnect, WSAEWOULDBLOCK if (!se.SocketErrorCode.Equals(SocketError.WouldBlock)) { ClientLog.LogError("Socket fatal exception, disconnect..."); this.Close(); return; } } catch (Exception e) { SetShowNetworkError(3, 0, SocketError.SocketError); ClientLog.LogError("receive msg failed : " + e.ToString()); } // finally { if (receiveHelper != null) { receiveHelper.socket.BeginReceive(receiveHelper.buffer, 0, receiveHelper.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMsgCallback), receiveHelper); } else { this.StartRecevieMsg(); } } }
// private void StartRecevieMsg() { #if USE_THREAD_RECEIVE_MSG if (null == mRecvThread) { mRecvThread = new Thread(RecvThreadDoWork); } // if (null != mRecvThread) { mThreadWork = true; mRecvThread.Start(); } #else MsgReceiveHelper receiveHelper = new MsgReceiveHelper(); receiveHelper.socket = this.socketClient; receiveHelper.buffer = new byte[DEFAULT_RECEIVE_SIZE]; this.socketClient.BeginReceive(receiveHelper.buffer, 0, receiveHelper.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMsgCallback), receiveHelper); #endif }