// ----------读取消息---------- private void _OnRead() { /* * Available 是从网络接收的、可供读取的数据字节数 * 这个值是缓冲区中已经接收数据的字节数,不是实际数据的字节数 */ if (m_Socket.Available > 0) { try { byte[] buffer = new byte[13]; // 接收数据 m_Socket.Receive(buffer, 13, SocketFlags.Peek); // 解析消息头 MessageHead head = MessageParse.UnparseHead(buffer); // 解析失败 if (head == null) { // ProtocolOption = 10042 Option unknown, or unsupported _OnError(new SocketException((int)SocketError.ProtocolOption)); } // 解析成功 else { // 13 = 4(HEAD) + 1(ProtoVersion) + 4(ServerVersion) + 4(Length) int length = head.Length + 13; // 数据全部到达 if (length <= m_Socket.Available) { buffer = new byte[length]; // 接收数据 m_Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); // 解析消息体 MessageBody body = MessageParse.UnparseBody(head.Length, buffer); if (body != null) { MessageData data = new MessageData() { head = head, body = body }; // 上锁,阻塞 lock (_lock) { m_Datas.Enqueue(data); } } else { // ProtocolOption = 10042 Option unknown, or unsupported _OnError(new SocketException((int)SocketError.ProtocolOption)); } } } } catch (SocketException e) { _OnError(e); } } }
// ----------递归地获取消息---------- void _OnData() { MessageHead head = MessageParse.UnparseHead(buffer.ToArray()); if (head == null) { isRead = false; return; } else { // 13 = 4(HEAD) + 1(ProtoVersion) + 4(ServerVersion) + 4(Length) int length = head.Length + 13; // 数据全部到达 if (length <= buffer.Count) { MessageBody body = MessageParse.UnparseBody(head.Length, buffer.ToArray()); if (body != null) { // 构造消息 MessageData data = new MessageData() { head = head, body = body }; // 消息入队 datas.Enqueue(data); // 移除缓冲区数据 buffer.RemoveRange(0, head.Length + 13); } else { // ProtocolOption = 10042 Option unknown, or unsupported _OnError(new SocketException((int)SocketError.ProtocolOption)); } } } // 递归调用 _OnData(); }