/// <summary> /// 转换为ArraySegment /// </summary> /// <param name="mask">是否打码</param> /// <returns></returns> public override unsafe ArraySegment <byte> ToArraySegment(bool mask) { var builder = new ByteBuilder(Endians.Big); ByteBits bits = (byte)this.Frame; bits[0] = this.Fin; builder.Add(bits); if (this.Content.Length > UInt16.MaxValue) { builder.Add(mask ? byte.MaxValue : (byte)127); builder.Add((ulong)this.Content.Length); } else if (this.Content.Length > 125) { builder.Add(mask ? (byte)254 : (byte)126); builder.Add((ushort)this.Content.Length); } else { var len = mask ? (byte)(this.Content.Length + 128) : (byte)this.Content.Length; builder.Add(len); } if (mask == true) { var maskingKey = ByteConverter.ToBytes(ran.Next(), Endians.Big); builder.Add(maskingKey); fixed(byte *pcontent = &this.Content[0], pmask = &maskingKey[0]) { for (var i = 0; i < this.Content.Length; i++) { *(pcontent + i) = (byte)(*(pcontent + i) ^ *(pmask + i % 4)); } } } builder.Add(this.Content); return(builder.ToArraySegment()); }
/// <summary> /// 转换为ArraySegment /// </summary> /// <returns></returns> public ArraySegment <byte> ToArraySegment() { var apiNameBytes = Encoding.UTF8.GetBytes(this.ApiName); var headLength = apiNameBytes.Length + 16; this.TotalBytes = this.Body == null ? headLength : headLength + this.Body.Length; this.ApiNameLength = (byte)apiNameBytes.Length; var builder = new ByteBuilder(Endians.Big); builder.Add(FastPacket.Mark); builder.Add(this.TotalBytes); builder.Add(this.ApiNameLength); builder.Add(apiNameBytes); builder.Add(this.Id); builder.Add(this.IsFromClient); builder.Add(this.IsException); builder.Add(this.Body); return(builder.ToArraySegment()); }
/// <summary> /// 输出内容块 /// </summary> /// <param name="buffer">内容</param> /// <param name="offset">偏移量</param> /// <param name="count">长度</param> /// <returns></returns> private bool WirteChunked(byte[] buffer, int offset, int count) { if (this.writeEnd == true) { return(false); } var builder = new ByteBuilder(Endians.Big); var size = Encoding.ASCII.GetBytes(Convert.ToString(count, 16)); builder.Add(size); builder.Add(CRLF); if (buffer != null) { builder.Add(buffer, offset, count); } builder.Add(CRLF); if (count == 0) { builder.Add(CRLF); } return(this.response.WriteContent(builder.ToArraySegment())); }