HandleResult OnReceive(TcpPullClient sender, int length) { // 数据到达了 // 需要长度 int required = pkgInfo.Length; // 剩余大小 int remain = length; while (remain >= required) { IntPtr bufferPtr = IntPtr.Zero; try { remain -= required; bufferPtr = Marshal.AllocHGlobal(required); if (sender.Fetch(bufferPtr, required) == FetchResult.Ok) { if (pkgInfo.IsHeader == true) { PkgHeader header = (PkgHeader)Marshal.PtrToStructure(bufferPtr, typeof(PkgHeader)); // 调试信息 Console.WriteLine("[Client] head -> Id: {0}, BodySize: {1}\r\n", header.Id, header.BodySize); required = header.BodySize; } else { // 调试信息 string recvString = Marshal.PtrToStringAnsi(bufferPtr, required); Console.WriteLine("[Client] body -> text: {0}\r\n", recvString); required = pkgHeaderSize; } AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", sender.ConnectionId, pkgInfo.Length)); pkgInfo.IsHeader = !pkgInfo.IsHeader; pkgInfo.Length = required; } } catch { return HandleResult.Error; } finally { if (bufferPtr != IntPtr.Zero) { Marshal.FreeHGlobal(bufferPtr); bufferPtr = IntPtr.Zero; } } } return HandleResult.Ok; }