private void ReceiveThread() { while (IsActive) { for (int i = 0; i < mClientSessions.Count; ++i) { Session clientSession = mClientSessions[i]; if (clientSession == null || clientSession.IsConnected == false) { continue; } try { int receiveSize = clientSession.TcpSocket.Receive(MessageBuffer.head, MessageBuffer.MESSAGE_HEAD_SIZE, SocketFlags.None); if (receiveSize == 0) { continue; // 消息大小为0 跳过 } if (receiveSize != MessageBuffer.MESSAGE_HEAD_SIZE) { continue; } if (MessageBuffer.IsValid(MessageBuffer.head) == false) { continue; } int bodySize = 0; if (MessageBuffer.Decode(MessageBuffer.head, MessageBuffer.MESSAGE_BODY_SIZE_OFFSET, ref bodySize) == false) { continue; } MessageBuffer message = new MessageBuffer(MessageBuffer.MESSAGE_HEAD_SIZE + bodySize); Array.Copy(MessageBuffer.head, 0, message.DataBuffer, 0, MessageBuffer.head.Length); if (bodySize > 0) { int receiveBodySize = clientSession.TcpSocket.Receive(message.DataBuffer, MessageBuffer.MESSAGE_BODY_OFFSET, bodySize, SocketFlags.None); if (receiveBodySize != bodySize) { continue; } } clientSession.OnReceiveMessageTCP(message); } catch (SocketException e) { Debug.Log("TCP SocketException 接收消息:" + e.Message); clientSession.Disconnect(); } catch (Exception e) { Debug.Error("TCP Exception 接收消息:" + e.Message); throw e; } } Thread.Sleep(1); } }
public void Disconnect() { mClient.Disconnect(); }