public void OnData(byte[] data, int offset, int length) { try { this._readStream.Write(data, offset, length); while (this._readStream.Length >= this._needLenth) { if (this._packetState == PacketState.ReadHead) { if (this._readStream.Length >= this._needLenth) //头部读取完毕 { long originPos = this._readStream.Position; this._readStream.Position = 0; this._readStream.Read(this.headBytes, 0, this.headBytes.Length); //从头部取出内容长度 int tmpIndex = 0; this._bodyLength = BitConverterNoAlloc.ToInt32(this.headBytes, ref tmpIndex); this._needLenth = this._bodyLength + this.headBytes.Length; //头部仍然在流中,所以加上头部的长度 this._packetState = PacketState.ReadBody; this._readStream.Position = originPos; //恢复流位置 } } if (this._packetState == PacketState.ReadBody) { if (this._readStream.Length >= this._needLenth) //内容读取完毕 { ArraySegment <byte> buffer; if (!this._readStream.TryGetBuffer(out buffer)) { throw new Exception("Get Buffer From Stream Error"); } //先将剩余部分写在交换流中 int remainLength = (int)(this._readStream.Length - this._needLenth); this._packetSwapStream.Write(buffer.Array, this._needLenth, remainLength); //定位到内容部分并调用回调 this._readStream.SetLength(this._needLenth); this._readStream.Position = this.headBytes.Length; this._onPacket(this._readStream); //重置包接收流并将剩余部分写入包接收流 this._readStream.Position = 0; this._readStream.SetLength(0); this._packetSwapStream.WriteTo(this._readStream); //重置交换流 this._packetSwapStream.Position = 0; this._packetSwapStream.SetLength(0); ResetPacket(); } } } } catch (Exception e) { this._onError(e); } }