/// <summary> /// Allocate or expand the decompression buffer, without exceeding the maximum allocation. /// Calls <see cref="DecompressionBufferExhausted(IByteBuffer)"/> if the buffer is full and cannot be expanded further. /// </summary> /// <param name="ctx"></param> /// <param name="buffer"></param> /// <param name="preferredSize"></param> /// <returns></returns> protected IByteBuffer PrepareDecompressBuffer(IChannelHandlerContext ctx, IByteBuffer buffer, int preferredSize) { if (buffer is null) { if (0u >= (uint)_maxAllocation) { return(ctx.Allocator.HeapBuffer(preferredSize)); } return(ctx.Allocator.HeapBuffer(Math.Min(preferredSize, _maxAllocation), _maxAllocation)); } // this always expands the buffer if possible, even if the expansion is less than preferredSize // we throw the exception only if the buffer could not be expanded at all // this means that one final attempt to deserialize will always be made with the buffer at maxAllocation if (buffer.EnsureWritable(preferredSize, true) == 1) { // buffer must be consumed so subclasses don't add it to output // we therefore duplicate it when calling decompressionBufferExhausted() to guarantee non-interference // but wait until after to consume it so the subclass can tell how much output is really in the buffer DecompressionBufferExhausted(buffer.Duplicate()); _ = buffer.SkipBytes(buffer.ReadableBytes); CThrowHelper.ThrowDecompressionException_Decompression_buffer_has_reached_maximum_size(buffer.MaxCapacity); } return(buffer); }
public override async void UserEventTriggered(IChannelHandlerContext context, object evt) { try { if (evt is IdleStateEvent) { PerformanceCounter cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total"); var percentage = cpu.NextValue(); Volatile.Read(ref percentage); percentage = cpu.NextValue(); GlobalMemoryStatus(ref MemInfo); var memory = MemInfo.dwMemoryLoad; var msg = $"{percentage},{memory},{{{string.Join(",", string.Empty)}}}"; _logWriter?.Info($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff")}:{msg}"); HEARTBEAT_SEQUENCE = Unpooled.UnreleasableBuffer(Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes("HEARTBEAT:" + msg))); try { await context.WriteAndFlushAsync(HEARTBEAT_SEQUENCE.Duplicate()); } catch (Exception e) { _logWriter?.Fatal($"{nameof(HeartbeatHandler)}.{nameof(UserEventTriggered)}:{e}"); } } else { base.UserEventTriggered(context, evt); } } catch (Exception e) { _logWriter?.Fatal($"{nameof(HeartbeatHandler)}.{nameof(UserEventTriggered)}:{e}"); } }
protected override void ChannelRead0(IChannelHandlerContext context, IFullHttpRequest request) { if (HttpUtil.Is100ContinueExpected(request)) { context.WriteAsync(new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.Continue, Unpooled.Empty)); } var keepAlive = HttpUtil.IsKeepAlive(request); var content = context.Allocator.Buffer(); content.WriteBytes(RESPONSE_BYTES.Duplicate()); ByteBufferUtil.WriteAscii(content, " - via " + request.ProtocolVersion + " (" + this.establishApproach + ")"); IFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK, content); response.Headers.Set(HttpHeaderNames.ContentType, "text/plain; charset=UTF-8"); response.Headers.SetInt(HttpHeaderNames.ContentLength, response.Content.ReadableBytes); if (keepAlive) { if (request.ProtocolVersion.Equals(HttpVersion.Http10)) { response.Headers.Set(HttpHeaderNames.Connection, HttpHeaderValues.KeepAlive); } context.WriteAsync(response); } else { // Tell the client we're going to close the connection. response.Headers.Set(HttpHeaderNames.Connection, HttpHeaderValues.Close); context.WriteAsync(response).CloseOnComplete(context.Channel); } }
async Task Process(IChannelHandlerContext ctx, IHttpRequest request) { string uri = request.Uri; switch (uri) { case "/lock": LockOper op2 = new LockOper() { Key = "key", Oper = "lock", Session = "session1" }; var ack1 = Task.Run(async() => { return(await this.BeginRequest(op2)); }).GetAwaiter().GetResult(); //byte[] json2 = Encoding.UTF8.GetBytes(NewMessage2().ToJsonFormat()); //this.WriteResponse(ctx, Unpooled.WrappedBuffer(json2), TypeJson, JsonClheaderValue); string str = "null"; if (ack1 != null) { str = Newtonsoft.Json.JsonConvert.SerializeObject(ack1); } byte[] json2 = Encoding.UTF8.GetBytes(new MessageBody(str).ToJsonFormat()); var length = json2.Length; this.WriteResponse(ctx, Unpooled.WrappedBuffer(json2), TypeJson, AsciiString.Cached($"{length}")); break; case "/plaintext": LockOper op = new LockOper() { Key = "key", Oper = "lock", Session = "session1" }; var ack = Task.Run(async() => { return(await this.BeginRequest(op)); }).GetAwaiter().GetResult(); this.WriteResponse(ctx, PlaintextContentBuffer.Duplicate(), TypePlain, PlaintextClheaderValue); break; case "/json": byte[] json = Encoding.UTF8.GetBytes(NewMessage().ToJsonFormat()); this.WriteResponse(ctx, Unpooled.WrappedBuffer(json), TypeJson, JsonClheaderValue); break; default: var response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound, Unpooled.Empty, false); await ctx.WriteAndFlushAsync(response); await ctx.CloseAsync(); break; } }
public IChannelBuffer GetBuffer(IByteBuffer nioBuffer) { if (nioBuffer.HasArray) { return(ChannelBuffers.WrappedBuffer(nioBuffer)); } IChannelBuffer buf = GetBuffer((IByteBuffer)nioBuffer.Duplicate()); int pos = nioBuffer.ReaderIndex; buf.WriteBytes(nioBuffer); nioBuffer.SetReaderIndex(pos); return(buf); }
public void DuplicateOfDuplicate() { IByteBuffer buf = Unpooled.Buffer(8).SetIndex(1, 7); IByteBuffer dup = buf.Duplicate().SetIndex(2, 6); IByteBuffer dup2 = dup.Duplicate(); Assert.NotSame(dup2, dup); Assert.IsAssignableFrom <UnpooledDuplicatedByteBuffer>(dup2); Assert.Same(dup2.Unwrap(), buf); Assert.Equal(dup2.ReaderIndex, dup.ReaderIndex); Assert.Equal(dup2.WriterIndex, dup.WriterIndex); Assert.Equal(dup2.Capacity, dup.Capacity); Assert.Equal(dup2.MaxCapacity, dup.MaxCapacity); }
/// <summary> /// Creates a new big-endian buffer whose content is a copy of the specified <see cref="Array" />. /// The new buffer's <see cref="IByteBuffer.ReaderIndex" /> and <see cref="IByteBuffer.WriterIndex" /> /// are <c>0</c> and <see cref="IByteBuffer.Capacity" /> respectively. /// </summary> /// <param name="buffer">A buffer we're going to copy.</param> /// <returns>The new buffer that copies the contents of <see cref="buffer" />.</returns> public static IByteBuffer CopiedBuffer(IByteBuffer buffer) { Contract.Requires(buffer != null); int length = buffer.ReadableBytes; if (length == 0) { return(Empty); } var copy = new byte[length]; // Duplicate the buffer so we do not adjust our position during our get operation IByteBuffer duplicate = buffer.Duplicate(); duplicate.GetBytes(0, copy); return(WrappedBuffer(copy).WithOrder(duplicate.Order)); }
public override void UserEventTriggered(IChannelHandlerContext context, object evt) { Console.WriteLine("ConnectorIdleStateTrigger.UserEventTriggered"); if (evt is IdleStateEvent) { IdleState state = ((IdleStateEvent)evt).State; if (state == IdleState.AllIdle) { // write heartbeat to server context.WriteAndFlushAsync(HEARTBEAT_SEQUENCE.Duplicate()); } } else { base.UserEventTriggered(context, evt); } }
protected override void ChannelRead0(IChannelHandlerContext ctx, IHttpRequest req) { if (HttpUtil.Is100ContinueExpected(req)) { ctx.WriteAsync(new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.Continue, Unpooled.Empty)); } IByteBuffer content = ctx.Allocator.Buffer(); content.WriteBytes(Response.Duplicate()); IFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK, content); response.Headers.Set(HttpHeaderNames.ContentType, "text/html; charset=UTF-8"); response.Headers.SetInt(HttpHeaderNames.ContentLength, response.Content.ReadableBytes); ctx.WriteAsync(response) .ContinueWith(t => ctx.CloseAsync(), TaskContinuationOptions.ExecuteSynchronously); }
void Process(IChannelHandlerContext context, IHttpRequest request) { string uri = request.Uri; switch (uri) { case "/plaintext": this.WriteResponse(context, PlaintextContentBuffer.Duplicate(), TypePlain, PlaintextClheaderValue, HttpUtil.IsKeepAlive(request)); break; case "/json": byte[] json = Encoding.UTF8.GetBytes(NewMessage().ToJsonFormat()); this.WriteResponse(context, Unpooled.WrappedBuffer(json), TypeJson, JsonClheaderValue, HttpUtil.IsKeepAlive(request)); break; default: var response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound, Unpooled.Empty, false); context.WriteAsync(response).CloseOnComplete(context.Channel); break; } }
private void Process(IChannelHandlerContext context, IHttpRequest request) { string uri = request.Uri; switch (uri) { case "/json": var json = Encoding.UTF8.GetBytes(_newMessage().ToJsonFormat()); WriteResponse(context, Unpooled.WrappedBuffer(json), _typeJson, _jsonClheaderValue); break; case "/404": var response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound, Unpooled.Empty, false); context.WriteAndFlushAsync(response); context.CloseAsync(); break; default: WriteResponse(context, _plaintextContentBuffer.Duplicate(), _typePlain, _plaintextClheaderValue); break; } }
public override void Encode(IChannelHandlerContext context, WebSocketFrame message, List <object> output) { if (message is TextWebSocketFrame) { // Text frame IByteBuffer data = message.Content; output.Add(_0X00.Duplicate()); output.Add(data.Retain()); output.Add(_0XFF.Duplicate()); } else if (message is CloseWebSocketFrame) { // Close frame, needs to call duplicate to allow multiple writes. // See https://github.com/netty/netty/issues/2768 output.Add(_0XFF_0X00.Duplicate()); } else { // Binary frame IByteBuffer data = message.Content; int dataLen = data.ReadableBytes; IByteBuffer buf = context.Allocator.Buffer(5); bool release = true; try { // Encode type. buf.WriteByte(0x80); // Encode length. int b1 = dataLen.RightUShift(28) & 0x7F; int b2 = dataLen.RightUShift(14) & 0x7F; int b3 = dataLen.RightUShift(7) & 0x7F; int b4 = dataLen & 0x7F; if (b1 == 0) { if (b2 == 0) { if (b3 == 0) { buf.WriteByte(b4); } else { buf.WriteByte(b3 | 0x80); buf.WriteByte(b4); } } else { buf.WriteByte(b2 | 0x80); buf.WriteByte(b3 | 0x80); buf.WriteByte(b4); } } else { buf.WriteByte(b1 | 0x80); buf.WriteByte(b2 | 0x80); buf.WriteByte(b3 | 0x80); buf.WriteByte(b4); } // Encode binary data. output.Add(buf); output.Add(data.Retain()); release = false; } finally { if (release) { buf.Release(); } } } }
/** * Returns the shared heartbeat content. */ public static IByteBuffer HeartbeatContent() { return(HEARTBEAT_BUF.Duplicate()); }
public virtual IByteBufferHolder Duplicate() => Replace(_data.Duplicate());
private IByteBuffer DecompressContent(IChannelHandlerContext ctx, WebSocketFrame msg) { if (_decoder is null) { switch (msg.Opcode) { case Opcode.Text: case Opcode.Binary: break; default: ThrowHelper.ThrowCodecException_UnexpectedInitialFrameType(msg); break; } _decoder = new EmbeddedChannel(ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.None)); } var readable = msg.Content.IsReadable(); var emptyDeflateBlock = EmptyDeflateBlock.Equals(msg.Content); _ = _decoder.WriteInbound(msg.Content.Retain()); if (AppendFrameTail(msg)) { _ = _decoder.WriteInbound(FrameTail.Duplicate()); } var compositeDecompressedContent = ctx.Allocator.CompositeBuffer(); for (; ;) { var partUncompressedContent = _decoder.ReadInbound <IByteBuffer>(); if (partUncompressedContent is null) { break; } if (!partUncompressedContent.IsReadable()) { _ = partUncompressedContent.Release(); continue; } _ = compositeDecompressedContent.AddComponent(true, partUncompressedContent); } // Correctly handle empty frames // See https://github.com/netty/netty/issues/4348 if (!emptyDeflateBlock && readable && compositeDecompressedContent.NumComponents <= 0) { // Sometimes after fragmentation the last frame // May contain left-over data that doesn't affect decompression if (!(msg is ContinuationWebSocketFrame)) { _ = compositeDecompressedContent.Release(); ThrowHelper.ThrowCodecException_CannotReadUncompressedBuf(); } } if (msg.IsFinalFragment && _noContext) { Cleanup(); } return(compositeDecompressedContent); }
public virtual IByteBuffer Duplicate() => Buf.Duplicate();
/// <summary> /// Creates a new big-endian buffer whose content is a copy of the specified <see cref="array"/>. /// The new buffer's <see cref="IByteBuffer.ReaderIndex"/> and <see cref="IByteBuffer.WriterIndex"/> /// are <c>0</c> and <see cref="IByteBuffer.Capacity"/> respectively. /// </summary> /// <param name="buffer">A buffer we're going to copy.</param> /// <returns>The new buffer that copies the contents of <see cref="buffer"/>.</returns> public static IByteBuffer CopiedBuffer(IByteBuffer buffer) { Contract.Requires(buffer != null); int length = buffer.ReadableBytes; if (length == 0) { return Empty; } byte[] copy = new byte[length]; // Duplicate the buffer so we do not adjust our position during our get operation IByteBuffer duplicate = buffer.Duplicate(); duplicate.GetBytes(0, copy); return WrappedBuffer(copy).WithOrder(duplicate.Order); }
public void FragmentedFrameWithLeftOverInLastFragment() { string hexDump = "677170647a777a737574656b707a787a6f6a7561756578756f6b7868616371716c657a6d64697479766d726f6" + "269746c6376777464776f6f72767a726f64667278676764687775786f6762766d776d706b76697773777a7072" + "6a6a737279707a7078697a6c69616d7461656d646278626d786f66666e686e776a7a7461746d7a776668776b6" + "f6f736e73746575637a6d727a7175707a6e74627578687871767771697a71766c64626d78726d6d7675756877" + "62667963626b687a726d676e646263776e67797264706d6c6863626577616967706a78636a72697464756e627" + "977616f79736475676f76736f7178746a7a7479626c64636b6b6778637768746c62"; EmbeddedChannel encoderChannel = new EmbeddedChannel( ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.None, 9, 15, 8)); EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerMessageDeflateDecoder(false)); IByteBuffer originPayload = Unpooled.WrappedBuffer(StringUtil.DecodeHexDump(hexDump)); Assert.True(encoderChannel.WriteOutbound(originPayload.Duplicate().Retain())); var compressedPayload = encoderChannel.ReadOutbound <IByteBuffer>(); compressedPayload = compressedPayload.Slice(0, compressedPayload.ReadableBytes - 4); int oneThird = compressedPayload.ReadableBytes / 3; TextWebSocketFrame compressedFrame1 = new TextWebSocketFrame( false, WebSocketRsv.Rsv1, compressedPayload.Slice(0, oneThird)); ContinuationWebSocketFrame compressedFrame2 = new ContinuationWebSocketFrame( false, WebSocketRsv.Rsv3, compressedPayload.Slice(oneThird, oneThird)); ContinuationWebSocketFrame compressedFrame3 = new ContinuationWebSocketFrame( false, WebSocketRsv.Rsv3, compressedPayload.Slice(oneThird * 2, oneThird)); int offset = oneThird * 3; ContinuationWebSocketFrame compressedFrameWithExtraData = new ContinuationWebSocketFrame( true, WebSocketRsv.Rsv3, compressedPayload.Slice(offset, compressedPayload.ReadableBytes - offset)); // check that last fragment contains only one extra byte Assert.Equal(1, compressedFrameWithExtraData.Content.ReadableBytes); Assert.Equal(1, compressedFrameWithExtraData.Content.GetByte(0)); // write compressed frames Assert.True(decoderChannel.WriteInbound(compressedFrame1.Retain())); Assert.True(decoderChannel.WriteInbound(compressedFrame2.Retain())); Assert.True(decoderChannel.WriteInbound(compressedFrame3.Retain())); Assert.True(decoderChannel.WriteInbound(compressedFrameWithExtraData)); // read uncompressed frames TextWebSocketFrame uncompressedFrame1 = decoderChannel.ReadInbound <TextWebSocketFrame>(); ContinuationWebSocketFrame uncompressedFrame2 = decoderChannel.ReadInbound <ContinuationWebSocketFrame>(); ContinuationWebSocketFrame uncompressedFrame3 = decoderChannel.ReadInbound <ContinuationWebSocketFrame>(); ContinuationWebSocketFrame uncompressedExtraData = decoderChannel.ReadInbound <ContinuationWebSocketFrame>(); Assert.False(uncompressedExtraData.Content.IsReadable()); var uncompressedPayload = Unpooled.WrappedBuffer(uncompressedFrame1.Content, uncompressedFrame2.Content, uncompressedFrame3.Content, uncompressedExtraData.Content); Assert.Equal(originPayload, uncompressedPayload); Assert.True(originPayload.Release()); Assert.True(uncompressedPayload.Release()); Assert.True(encoderChannel.FinishAndReleaseAll()); Assert.False(decoderChannel.Finish()); }
protected override void Encode(IChannelHandlerContext context, WebSocketFrame message, List <object> output) { switch (message.Opcode) { case Opcode.Text: // Text frame IByteBuffer data0 = message.Content; output.Add(_0X00.Duplicate()); output.Add(data0.Retain()); output.Add(_0XFF.Duplicate()); break; case Opcode.Close: // Close frame, needs to call duplicate to allow multiple writes. // See https://github.com/netty/netty/issues/2768 output.Add(_0XFF_0X00.Duplicate()); break; default: // Binary frame IByteBuffer data = message.Content; int dataLen = data.ReadableBytes; IByteBuffer buf = context.Allocator.Buffer(5); bool release = true; try { // Encode type. _ = buf.WriteByte(0x80); // Encode length. int b1 = dataLen.RightUShift(28) & 0x7F; int b2 = dataLen.RightUShift(14) & 0x7F; int b3 = dataLen.RightUShift(7) & 0x7F; int b4 = dataLen & 0x7F; if (0u >= (uint)b1) { if (0u >= (uint)b2) { if (0u >= (uint)b3) { _ = buf.WriteByte(b4); } else { _ = buf.WriteByte(b3 | 0x80); _ = buf.WriteByte(b4); } } else { _ = buf.WriteByte(b2 | 0x80); _ = buf.WriteByte(b3 | 0x80); _ = buf.WriteByte(b4); } } else { _ = buf.WriteByte(b1 | 0x80); _ = buf.WriteByte(b2 | 0x80); _ = buf.WriteByte(b3 | 0x80); _ = buf.WriteByte(b4); } // Encode binary data. output.Add(buf); output.Add(data.Retain()); release = false; } finally { if (release) { _ = buf.Release(); } } break; } }
public void Response(IChannelHandlerContext ctx) { this.WriteResponse(ctx, PlaintextContentBuffer.Duplicate(), TypePlain, PlaintextClheaderValue); }