public SetLength ( long value ) : void | ||
value | long | The desired length of the current stream in bytes. |
리턴 | void |
/// <summary> /// Gets the frame bytes. /// </summary> /// <returns></returns> public Stream GetFrameBytes(bool compress, int compressTreshold) { var buffer = new PoolMemoryStream(); buffer.WriteByte((byte)Version); buffer.WriteByte((byte)Flags); buffer.WriteByte(unchecked((byte)Stream)); buffer.WriteByte((byte)OpCode); //write length placeholder buffer.WriteInt(0); //write uncompressed data WriteData(buffer); //compress if allowed, and buffer is large enough to compress if (compress && buffer.Length > compressTreshold + 8) { buffer.Position = 8; //compress data to temporary stream using (var compressed = new PoolMemoryStream()) { //compress the data to the buffer int length = Compressor.Compress(buffer, compressed); //add compression to flags Flags |= FrameFlags.Compression; buffer.Position = 1; buffer.WriteByte((byte)Flags); //overwrite data with compressed data buffer.Position = 8; compressed.Position = 0; compressed.CopyTo(buffer); buffer.SetLength(length + 8); } } //overwrite length with real value buffer.Position = 4; buffer.WriteInt((int)buffer.Length - 8); //reset buffer position buffer.Position = 0; //return the buffer return buffer; }
/// <summary> /// Gets the frame bytes. /// </summary> /// <returns> </returns> public PoolMemoryStream GetFrameBytes(bool compress, int compressTreshold) { var buffer = new PoolMemoryStream(); int versionByte = (ProtocolVersion & 0x7f) | (IsRequest ? 0 : 0x80); buffer.WriteByte((byte)versionByte); buffer.WriteByte((byte)Flags); if(ProtocolVersion <= 2) buffer.WriteByte(unchecked((byte)Stream)); else buffer.WriteShort(unchecked((ushort)Stream)); buffer.WriteByte((byte)OpCode); //write length placeholder buffer.WriteInt(0); long headerLength = buffer.Position; //write uncompressed data WriteData(buffer); //compress if allowed, and buffer is large enough to compress if(compress && buffer.Length > headerLength + compressTreshold) { //rewind to start of content buffer.Position = headerLength; //compress data to temporary stream using(var compressed = new PoolMemoryStream()) { //compress the data to the buffer int length = Compressor.Compress(buffer, compressed); //add compression to flags Flags |= FrameFlags.Compression; buffer.Position = 1; buffer.WriteByte((byte)Flags); //overwrite data with compressed data buffer.Position = headerLength; compressed.Position = 0; compressed.CopyTo(buffer); buffer.SetLength(headerLength + length); } } //overwrite length with real value buffer.Position = headerLength - 4; buffer.WriteInt((int)(buffer.Length - headerLength)); //reset buffer position buffer.Position = 0; //return the buffer return buffer; }