void ReceiveCallback(IAsyncResult ar) { try { var state = (StateObject)ar.AsyncState; var s = state.m_Socket; int bytesRead = s.EndReceive(ar); if (bytesRead > 0) { //增加读取的索引 state.m_BufferReceivedSize += bytesRead; //拆分包 TcpTools.SplitPack(ref state.m_Buffer, ref state.m_BufferReceivedSize, ref state.m_BufferSize, OnRecvPack); //继续接收 s.BeginReceive(state.m_Buffer, state.m_BufferReceivedSize, state.m_BufferSize - state.m_BufferReceivedSize, 0, new AsyncCallback(ReceiveCallback), state); } else { Close(); AddEvent(TcpEventType.EventReceiveData, SocketError.NoData, "NoData"); } } catch (SocketException e) { Close(); AddEvent(TcpEventType.EventReceiveData, e.SocketErrorCode, e.Message); } }
void HandleDataReceived(IAsyncResult ar) { if (IsRunning) { var client = ar.AsyncState as Socket; try { int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { m_BufferReceivedSize += bytesRead; TcpTools.SplitPack(ref m_Buffer, ref m_BufferReceivedSize, ref m_BufferSize, PushPack); client.BeginReceive(m_Buffer, m_BufferReceivedSize, m_BufferSize - m_BufferReceivedSize, SocketFlags.None, new AsyncCallback(HandleDataReceived), client); } else { Close(); } } catch (SocketException) { Close(); } } }
void OnRecvPack(byte[] pack) { if (!IsConnected) { TcpLogger.LogError("Socket not connected, recvied pack will be drop."); return; } pack = TcpTools.Decode(pack, m_AesDecryptor, ref m_RecvIdx);//解压缩,解加密 m_RecvQueue.Enqueue(pack); }
void BeginSend(byte[] data) { try { data = TcpTools.Encode(data, m_AesEncryptor, CurSendIdx); m_Socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), m_Socket); } catch (SocketException e) { Close(); AddEvent(TcpEventType.EventSendData, e.SocketErrorCode, e.Message); } }
void PushPack(byte[] pack) { pack = TcpTools.Decode(pack, m_AesDecryptor, ref m_RecvIdx);//解压缩,解加密 m_RecvQueue.Enqueue(pack); }