private void sendBody(Socket soc, NetServiceChannel channel, string str, byte[] data) { #if NET_DEBUG sendStopwatch.Start(); #endif //lock (soc) { byte[] content = Encoding.UTF8.GetBytes(str); int length; byte[] body = GZip(content, 0, out length); if (DebugLevel > 1) { if (JObject.Parse(str)["Type"].ToString() != "Beat") { Debug.Log(String.Format("<<< ch:{3} sending {0}->{1} body:{2}", content.Length, length, str, channel)); } } Header header = new Header { Sign = SIGN, Channel = (uint)channel, Bodysize = (uint)length, ContentSize = (uint)content.Length, }; header.DataSize = (data == null) ? 0 : (uint)data.Length; byte[] head = headerRawSerializer.RawSerialize(header); soc.SendTimeout = 10000; if (soc.Send(head) != Marshal.SizeOf(typeof(Header))) { throw new Exception("send header failed"); } soc.SendTimeout = 30000; if (soc.Send(body, length, SocketFlags.None) != length) { throw new Exception("send body failed"); } if (data != null) { if (soc.Send(data) != data.Length) { throw new Exception("send data failed"); } } } #if NET_DEBUG sendCount++; sendStopwatch.Stop(); #endif }
private string recvBody(Socket soc, ref NetServiceChannel channel, ref byte[] data) { #if NET_DEBUG recvStopwatch.Start(); #endif var headSize = Marshal.SizeOf(typeof(Header)); var head = new byte[headSize]; var headRead = 0; while (headRead < headSize) { soc.ReceiveTimeout = ReceiveTimeout; var n = soc.Receive(head, headRead, headSize - headRead, SocketFlags.None); headRead += n; } if (headRead != headSize) { throw new Exception("recv header failed " + headRead.ToString()); } Header header = headerRawSerializer.RawDeserialize(head); if (header.Sign != SIGN) { throw new Exception("recv header sign mismatch"); } channel = (NetServiceChannel)header.Channel; var bytesExpected = (int)header.Bodysize; var body = new byte[bytesExpected]; var bytesRead = 0; while (bytesRead < bytesExpected) { soc.ReceiveTimeout = 10000; var n = soc.Receive(body, bytesRead, bytesExpected - bytesRead, SocketFlags.None); bytesRead += n; } int length; byte[] content = GZip(body, (int)header.ContentSize, out length); if (length != header.ContentSize) { throw new Exception("received body content size mismatch"); } string str = Encoding.UTF8.GetString(content, 0, length); if (DebugLevel > 1) { Console.WriteLine(String.Format(">>> ch:{3} receiving {0}->{1} body:{2}", header.ContentSize, header.Bodysize, str, channel)); } data = null; if (header.DataSize > 0) { var dataExpected = (int)header.DataSize; data = new byte[dataExpected]; var dataRead = 0; while (dataRead < dataExpected) { soc.ReceiveTimeout = 30000; var n = soc.Receive(data, dataRead, dataExpected - dataRead, SocketFlags.None); dataRead += n; } } #if NET_DEBUG recvCount++; recvStopwatch.Stop(); #endif return(str); }