/// <summary> /// 接收消息线程方法 /// </summary> /// <param name="clientSocket"></param> protected void Receive() { int bufferLength = 1024 * 1024 * 16; byte[] buffer = new byte[bufferLength]; while (true) { int length = 0; int totalLength = 0; byte[] received = null; using (MemoryStream stream = new MemoryStream()) { try { Stopwatch sw = Stopwatch.StartNew(); while (true) { try { length = ClientSocket.Receive(buffer); } catch (ObjectDisposedException) { return; } stream.Write(buffer, 0, length); totalLength += length; bool end = true; if (length < SocketEnd.Length) { continue; } for (int i = length - SocketEnd.Length, j = 0; i < length; i++, j++) { if (buffer[i] != SocketEnd[j]) { end = false; break; } } if (end) { break; } } } catch (SocketException ex) { if (ex.SocketErrorCode != SocketError.TimedOut) { SocketClosedByAccident?.Invoke(this, new SocketClosedByAccidentEventArgs(ex)); return; } } stream.Flush(); received = stream.ToArray(); } byte command = received[0]; byte[] data = new byte[totalLength - 1 - SocketEnd.Length]; if (data.Length > 0) { Array.Copy(received.ToArray(), 1, data, 0, totalLength - 1 - SocketEnd.Length); } DataReceived?.Invoke(this, new DataReceivedEventArgs(command, data)); } }
/// <summary> /// 接收消息线程方法 /// </summary> /// <param name="clientSocket"></param> protected void Receive() { int bufferLength = 1024 * 1024 * 16; byte[] buffer = new byte[bufferLength]; while (true) { int length = 0; int totalLength = 0; byte[] received = null; CommandBody content = null; using (MemoryStream stream = new MemoryStream()) { try { Stopwatch sw = Stopwatch.StartNew(); while (true) { try { length = ClientSocket.Receive(buffer); } catch (ObjectDisposedException) { return; } stream.Write(buffer, 0, length); totalLength += length; bool end = true; if (length < SocketEnd.Length) { continue; } for (int i = length - SocketEnd.Length, j = 0; i < length; i++, j++) { if (buffer[i] != SocketEnd[j]) { end = false; break; } } if (end) { break; } } } catch (SocketException ex) { if (ex.SocketErrorCode != SocketError.TimedOut) { SocketClosedByAccident?.Invoke(this, new SocketClosedByAccidentEventArgs(ex)); return; } } stream.Flush(); //received = stream.ToArray(); //stream.Seek(0, SeekOrigin.Begin); //received = new byte[totalLength - SocketEnd.Length]; //stream.Read(received, 0, totalLength - SocketEnd.Length); stream.SetLength(totalLength - SocketEnd.Length); stream.Seek(0, SeekOrigin.Begin); content = Deserialize(stream); } tttt += totalLength; Debug.WriteLine("收到的长度:" + tttt); //byte command = received[0]; //byte[] data = new byte[totalLength - 1 - SocketEnd.Length]; //if (data.Length > 0) //{ // Array.Copy(received.ToArray(), 1, data, 0, totalLength - 1 - SocketEnd.Length); //} DataReceived?.Invoke(this, new DataReceivedEventArgs(content)); } }