Example #1
0
        private void AssertCorruptedFrameExceptionHandling(byte[] data)
        {
            EmbeddedChannel    channel = new EmbeddedChannel(new Utf8FrameValidator());
            TextWebSocketFrame frame   = new TextWebSocketFrame(Unpooled.CopiedBuffer(data));

            try
            {
                channel.WriteInbound(frame);
                Assert.False(true);
            }
            catch (Exception exc)
            {
                Assert.NotNull(exc as CorruptedFrameException);
                Assert.IsType <CorruptedWebSocketFrameException>(exc);
            }
            Assert.True(channel.Finish());
            var buf = channel.ReadOutbound <IByteBuffer>();

            Assert.NotNull(buf);
            try
            {
                Assert.False(buf.IsReadable());
            }
            finally
            {
                buf.Release();
            }
            Assert.Null(channel.ReadOutbound());
            Assert.Equal(0, frame.ReferenceCount);
        }
Example #2
0
        static void Main(string[] args)
        {
            var client = DotNettyServiceProvider.Current.GetRequiredService <IWebSocketClient>();

            client.StartAsync(async channel =>
            {
                while (true)
                {
                    string msg = Console.ReadLine();
                    if (msg.IsNull())
                    {
                        break;
                    }
                    else if ("bye".Equals(msg, StringComparison.OrdinalIgnoreCase))
                    {
                        await channel.WriteAndFlushAsync(new CloseWebSocketFrame());
                        break;
                    }
                    else if ("ping".Equals(msg, StringComparison.OrdinalIgnoreCase))
                    {
                        var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                        await channel.WriteAndFlushAsync(frame);
                    }
                    else
                    {
                        var frame = new TextWebSocketFrame(msg);
                        await channel.WriteAndFlushAsync(frame);
                    }
                }

                await channel.CloseAsync();
            })
            .Wait();
        }
        public void TestNeverSkip()
        {
            IWebSocketExtensionFilter neverSkip = NeverSkipWebSocketExtensionFilter.Instance;

            BinaryWebSocketFrame binaryFrame = new BinaryWebSocketFrame();

            Assert.False(neverSkip.MustSkip(binaryFrame));
            Assert.True(binaryFrame.Release());

            TextWebSocketFrame textFrame = new TextWebSocketFrame();

            Assert.False(neverSkip.MustSkip(textFrame));
            Assert.True(textFrame.Release());

            PingWebSocketFrame pingFrame = new PingWebSocketFrame();

            Assert.False(neverSkip.MustSkip(pingFrame));
            Assert.True(pingFrame.Release());

            PongWebSocketFrame pongFrame = new PongWebSocketFrame();

            Assert.False(neverSkip.MustSkip(pongFrame));
            Assert.True(pongFrame.Release());

            CloseWebSocketFrame closeFrame = new CloseWebSocketFrame();

            Assert.False(neverSkip.MustSkip(closeFrame));
            Assert.True(closeFrame.Release());

            ContinuationWebSocketFrame continuationFrame = new ContinuationWebSocketFrame();

            Assert.False(neverSkip.MustSkip(continuationFrame));
            Assert.True(continuationFrame.Release());
        }
Example #4
0
        public void CodecExceptionForNotFinEmptyFrame()
        {
            EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false));

            TextWebSocketFrame emptyNotFinFrame = new TextWebSocketFrame(false, 0, "");

            try
            {
                encoderChannel.WriteOutbound(emptyNotFinFrame);
                Assert.False(true);
            }
            catch (Exception exc)
            {
                if (exc is AggregateException aggregateException)
                {
                    Assert.IsType <EncoderException>(aggregateException.InnerException);
                }
                else
                {
                    Assert.IsType <EncoderException>(exc);
                }
            }
            finally
            {
                // EmptyByteBuf buffer
                Assert.False(emptyNotFinFrame.Release());
                Assert.False(encoderChannel.Finish());
            }
        }
Example #5
0
        protected override void Decode(IChannelHandlerContext ctx, WebSocketFrame msg, List <object> output)
        {
            var decompressedContent = DecompressContent(ctx, msg);

            WebSocketFrame outMsg = null;

            switch (msg.Opcode)
            {
            case Opcode.Text:
                outMsg = new TextWebSocketFrame(msg.IsFinalFragment, NewRsv(msg), decompressedContent);
                break;

            case Opcode.Binary:
                outMsg = new BinaryWebSocketFrame(msg.IsFinalFragment, NewRsv(msg), decompressedContent);
                break;

            case Opcode.Cont:
                outMsg = new ContinuationWebSocketFrame(msg.IsFinalFragment, NewRsv(msg), decompressedContent);
                break;

            default:
                ThrowHelper.ThrowCodecException_UnexpectedFrameType(msg);
                break;
            }
            output.Add(outMsg);
        }
Example #6
0
        public async Task SendCommandByStringAsync(ICommand command)
        {
            string         commandJson = command.ToJson();
            WebSocketFrame frame       = new TextWebSocketFrame(commandJson);

            await SendMessageAsync(frame);

            _clientHandler.OnSendMessage(commandJson);
        }
Example #7
0
        public void TextFrame()
        {
            var channel = new EmbeddedChannel(new Handler());

            var textFrame = new TextWebSocketFrame();

            Assert.True(channel.WriteInbound(textFrame));

            AssertPropagatedInbound(textFrame, channel);

            textFrame.Release();
            Assert.False(channel.Finish());
        }
Example #8
0
 public async Task ExcuteAsync(IChannelHandlerContext ctx, object commandData)
 {
     if (!(commandData is string commandJson))
     {
         throw new ApplicationException("命令数据错误");
     }
     ConsoleHelper.TestWriteLine(commandJson, "接受到命令");
     var @event = new TestEvent
     {
         StringData = "服务器返回"
     };
     var eventJson = new TextWebSocketFrame(@event.ToJson());
     await ctx.WriteAndFlushAsync(eventJson);
 }
        public void EmptyFrameDecompression()
        {
            EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerMessageDeflateDecoder(false));

            TextWebSocketFrame emptyDeflateBlockFrame = new TextWebSocketFrame(true, WebSocketRsv.Rsv1, DeflateDecoder.EmptyDeflateBlock);

            Assert.True(decoderChannel.WriteInbound(emptyDeflateBlockFrame));
            var emptyBufferFrame = decoderChannel.ReadInbound <TextWebSocketFrame>();

            Assert.False(emptyBufferFrame.Content.IsReadable());

            // Composite empty buffer
            Assert.True(emptyBufferFrame.Release());
            Assert.False(decoderChannel.Finish());
        }
Example #10
0
        public void EmptyFrameCompression()
        {
            EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false));

            TextWebSocketFrame emptyFrame = new TextWebSocketFrame("");

            Assert.True(encoderChannel.WriteOutbound(emptyFrame));
            var emptyDeflateFrame = encoderChannel.ReadOutbound <TextWebSocketFrame>();

            Assert.Equal(WebSocketRsv.Rsv1, emptyDeflateFrame.Rsv);
            Assert.True(ByteBufferUtil.Equals(DeflateDecoder.EmptyDeflateBlock, emptyDeflateFrame.Content));
            // Unreleasable buffer
            Assert.False(emptyDeflateFrame.Release());

            Assert.False(encoderChannel.Finish());
        }
Example #11
0
        internal ResponseJsonMessage SendRequest(RequestJsonMessage msg)
        {
            var id = Guid.NewGuid().ToString();

            allWaits.Add(id);
            msg.MsgId = id;
            WebSocketFrame frame = new TextWebSocketFrame(msg.ToBuffer());

            if (!channel.Active)
            {
                //ThrowError("服务端已断开连接", "500");
            }
            channel.WriteAndFlushAsync(frame);

            //等待返回
            var response = allWaits.Wait(id).Response;

            return(response);
        }
Example #12
0
        public bool SendMessage <T>(string clientKey, T msg, out string error)
        {
            error = "";
            var a = clientKeys.TryGetValue(clientKey, out IChannelHandlerContext ctx);

            if (!a)
            {
                error = "找不到客户端连接";
                return(false);
            }
            var response = new ResponseJsonMessage()
            {
                Data = msg.ToJson(), MsgType = typeof(T).Name
            };
            var frame2 = new TextWebSocketFrame(response.ToJson());

            ctx.WriteAndFlushAsync(frame2);
            return(true);
        }
Example #13
0
        void HandleWebSocketFrame(IChannelHandlerContext ctx, WebSocketFrame frame)
        {
            // Check for closing frame
            if (frame is CloseWebSocketFrame)
            {
                this.handshaker.CloseAsync(ctx.Channel, (CloseWebSocketFrame)frame.Retain());
                server.RemoveClient(ctx);
                return;
            }

            if (frame is PingWebSocketFrame)
            {
                //ctx.WriteAsync(new PongWebSocketFrame((IByteBuffer)frame.Content.Retain()));
                //Console.WriteLine("PingWebSocketFrame");
                //server.AddClient(ctx);
                return;
            }

            if (frame is TextWebSocketFrame)
            {
                var data = ((TextWebSocketFrame)frame).Text();
                //Console.WriteLine("收到消息:" + data);
                var request = RequestJsonMessage.FromBuffer(data);
                // Echo the frame
                var result = server.InvokeResult2(ctx, request) as ResponseJsonMessage;
                if (result == null)
                {
                    return;
                }
                result.MsgId = request.MsgId;
                var frame2 = new TextWebSocketFrame(result.ToBuffer());
                ctx.WriteAsync(frame2);
                //Console.WriteLine("发送回复");
                return;
            }

            if (frame is BinaryWebSocketFrame)
            {
                // Echo the frame
                ctx.WriteAsync(frame.Retain());
            }
        }
Example #14
0
        public void SelectivityCompressionSkip()
        {
            var             selectivityCompressionFilter = new SelectivityDecompressionFilter0();
            EmbeddedChannel encoderChannel = new EmbeddedChannel(
                new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter));
            EmbeddedChannel decoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.None));

            string textPayload = "not compressed payload";

            byte[] binaryPayload = new byte[101];
            _random.NextBytes(binaryPayload);

            WebSocketFrame       textFrame   = new TextWebSocketFrame(textPayload);
            BinaryWebSocketFrame binaryFrame = new BinaryWebSocketFrame(Unpooled.WrappedBuffer(binaryPayload));

            Assert.True(encoderChannel.WriteOutbound(textFrame));
            Assert.True(encoderChannel.WriteOutbound(binaryFrame));

            var outboundTextFrame = encoderChannel.ReadOutbound <WebSocketFrame>();

            //compression skipped for textFrame
            Assert.Equal(0, outboundTextFrame.Rsv);
            Assert.Equal(textPayload, outboundTextFrame.Content.ToString(Encoding.UTF8));
            Assert.True(outboundTextFrame.Release());

            var outboundBinaryFrame = encoderChannel.ReadOutbound <WebSocketFrame>();

            //compression not skipped for binaryFrame
            Assert.Equal(WebSocketRsv.Rsv1, outboundBinaryFrame.Rsv);

            Assert.True(decoderChannel.WriteInbound(outboundBinaryFrame.Content.Retain()));
            var uncompressedBinaryPayload = decoderChannel.ReadInbound <IByteBuffer>();

            Assert.Equal(binaryPayload, ByteBufferUtil.GetBytes(uncompressedBinaryPayload));

            Assert.True(outboundBinaryFrame.Release());
            Assert.True(uncompressedBinaryPayload.Release());

            Assert.False(encoderChannel.Finish());
            Assert.False(decoderChannel.Finish());
        }
Example #15
0
        protected override void Encode(IChannelHandlerContext ctx, WebSocketFrame msg, List <object> output)
        {
            IByteBuffer compressedContent = null;

            if (msg.Content.IsReadable())
            {
                compressedContent = CompressContent(ctx, msg);
            }
            else if (msg.IsFinalFragment)
            {
                // Set empty DEFLATE block manually for unknown buffer size
                // https://tools.ietf.org/html/rfc7692#section-7.2.3.6
                compressedContent = DeflateDecoder.EmptyDeflateBlock.Duplicate();
            }
            else
            {
                ThrowHelper.ThrowCodecException_CannotCompressContentBuffer();
            }

            WebSocketFrame outMsg = null;

            switch (msg.Opcode)
            {
            case Opcode.Text:
                outMsg = new TextWebSocketFrame(msg.IsFinalFragment, Rsv(msg), compressedContent);
                break;

            case Opcode.Binary:
                outMsg = new BinaryWebSocketFrame(msg.IsFinalFragment, Rsv(msg), compressedContent);
                break;

            case Opcode.Cont:
                outMsg = new ContinuationWebSocketFrame(msg.IsFinalFragment, Rsv(msg), compressedContent);
                break;

            default:
                ThrowHelper.ThrowCodecException_UnexpectedFrameType(msg);
                break;
            }
            output.Add(outMsg);
        }
        public void SelectivityDecompressionSkip()
        {
            var             selectivityDecompressionFilter = new SelectivityDecompressionFilter0();
            EmbeddedChannel encoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.None, 9, 15, 8));
            EmbeddedChannel decoderChannel = new EmbeddedChannel(
                new PerMessageDeflateDecoder(false, selectivityDecompressionFilter));

            string textPayload = "compressed payload";

            byte[] binaryPayload = new byte[300];
            _random.NextBytes(binaryPayload);

            Assert.True(encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(textPayload))));
            Assert.True(encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(binaryPayload)));
            var compressedTextPayload   = encoderChannel.ReadOutbound <IByteBuffer>();
            var compressedBinaryPayload = encoderChannel.ReadOutbound <IByteBuffer>();

            TextWebSocketFrame   compressedTextFrame   = new TextWebSocketFrame(true, WebSocketRsv.Rsv1, compressedTextPayload);
            BinaryWebSocketFrame compressedBinaryFrame = new BinaryWebSocketFrame(true, WebSocketRsv.Rsv1, compressedBinaryPayload);

            Assert.True(decoderChannel.WriteInbound(compressedTextFrame));
            Assert.True(decoderChannel.WriteInbound(compressedBinaryFrame));

            var inboundTextFrame   = decoderChannel.ReadInbound <TextWebSocketFrame>();
            var inboundBinaryFrame = decoderChannel.ReadInbound <BinaryWebSocketFrame>();

            Assert.Equal(WebSocketRsv.Rsv1, inboundTextFrame.Rsv);
            Assert.Equal(compressedTextPayload, inboundTextFrame.Content);
            Assert.True(inboundTextFrame.Release());

            Assert.Equal(0, inboundBinaryFrame.Rsv);
            Assert.Equal(binaryPayload, ByteBufferUtil.GetBytes(inboundBinaryFrame.Content));
            Assert.True(inboundBinaryFrame.Release());

            Assert.True(encoderChannel.FinishAndReleaseAll());
            Assert.False(decoderChannel.Finish());
        }
Example #17
0
        static async Task RunClientAsync()
        {
            var builder = new UriBuilder
            {
                Scheme = ClientSettings.IsSsl ? "wss" : "ws",
                Host   = ClientSettings.Host.ToString(),
                Port   = ClientSettings.Port
            };

            string path = ExampleHelper.Configuration["path"];

            if (!string.IsNullOrEmpty(path))
            {
                builder.Path = path;
            }

            Uri uri = builder.Uri;

            ExampleHelper.SetConsoleLogger();

            bool useLibuv = ClientSettings.UseLibuv;

            Console.WriteLine("Transport type : " + (useLibuv ? "Libuv" : "Socket"));

            IEventLoopGroup group;

            if (useLibuv)
            {
                group = new EventLoopGroup();
            }
            else
            {
                group = new MultithreadEventLoopGroup();
            }

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Option(ChannelOption.TcpNodelay, true);
                if (useLibuv)
                {
                    bootstrap.Channel <TcpChannel>();
                }
                else
                {
                    bootstrap.Channel <TcpSocketChannel>();
                }

                // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
                // If you change it to V00, ping is not supported and remember to change
                // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
                var handler = new WebSocketClientHandler(
                    WebSocketClientHandshakerFactory.NewHandshaker(
                        uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()));

                bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (cert != null)
                    {
                        pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                    }

                    pipeline.AddLast(
                        new HttpClientCodec(),
                        new HttpObjectAggregator(8192),
                        WebSocketClientCompressionHandler.Instance,
                        handler);
                }));

                IChannel ch = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port));

                await handler.HandshakeCompletion;

                Console.WriteLine("WebSocket handshake completed.\n");
                Console.WriteLine("\t[bye]:Quit \n\t [ping]:Send ping frame\n\t Enter any text and Enter: Send text frame");
                while (true)
                {
                    string msg = Console.ReadLine();
                    if (msg == null)
                    {
                        break;
                    }
                    else if ("bye".Equals(msg.ToLower()))
                    {
                        await ch.WriteAndFlushAsync(new CloseWebSocketFrame());

                        break;
                    }
                    else if ("ping".Equals(msg.ToLower()))
                    {
                        var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                        await ch.WriteAndFlushAsync(frame);
                    }
                    else
                    {
                        WebSocketFrame frame = new TextWebSocketFrame(msg);
                        await ch.WriteAndFlushAsync(frame);
                    }
                }

                await ch.CloseAsync();
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Example #18
0
        protected internal override void Decode(IChannelHandlerContext ctx, WebSocketFrame msg, List <object> output)
        {
            if (this.decoder == null)
            {
                if (!(msg is TextWebSocketFrame) && !(msg is BinaryWebSocketFrame))
                {
                    throw new CodecException($"unexpected initial frame type: {msg.GetType().Name}");
                }

                this.decoder = new EmbeddedChannel(ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.None));
            }

            bool readable = msg.Content.IsReadable();

            this.decoder.WriteInbound(msg.Content.Retain());
            if (this.AppendFrameTail(msg))
            {
                this.decoder.WriteInbound(Unpooled.WrappedBuffer(FrameTail));
            }

            CompositeByteBuffer compositeUncompressedContent = ctx.Allocator.CompositeDirectBuffer();

            for (;;)
            {
                var partUncompressedContent = this.decoder.ReadInbound <IByteBuffer>();
                if (partUncompressedContent == null)
                {
                    break;
                }

                if (!partUncompressedContent.IsReadable())
                {
                    partUncompressedContent.Release();
                    continue;
                }

                compositeUncompressedContent.AddComponent(true, partUncompressedContent);
            }

            // Correctly handle empty frames
            // See https://github.com/netty/netty/issues/4348
            if (readable && compositeUncompressedContent.NumComponents <= 0)
            {
                compositeUncompressedContent.Release();
                throw new CodecException("cannot read uncompressed buffer");
            }

            if (msg.IsFinalFragment && this.noContext)
            {
                this.Cleanup();
            }

            WebSocketFrame outMsg;

            if (msg is TextWebSocketFrame)
            {
                outMsg = new TextWebSocketFrame(msg.IsFinalFragment, this.NewRsv(msg), compositeUncompressedContent);
            }
            else if (msg is BinaryWebSocketFrame)
            {
                outMsg = new BinaryWebSocketFrame(msg.IsFinalFragment, this.NewRsv(msg), compositeUncompressedContent);
            }
            else if (msg is ContinuationWebSocketFrame)
            {
                outMsg = new ContinuationWebSocketFrame(msg.IsFinalFragment, this.NewRsv(msg), compositeUncompressedContent);
            }
            else
            {
                throw new CodecException($"unexpected frame type: {msg.GetType().Name}");
            }

            output.Add(outMsg);
        }
        public void DecoderNoClientContext()
        {
            PerMessageDeflateClientExtensionHandshaker handshaker =
                new PerMessageDeflateClientExtensionHandshaker(6, true, MaxWindowSize, true, false);

            sbyte[] firstPayload = new sbyte[] {
                76, -50, -53, 10, -62, 48, 20, 4, -48, 95, 41, 89, -37, 36, 77, 90, 31, -39, 41, -72, 112, 33, -120, 20,
                20, 119, -79, 70, 123, -95, 121, -48, 92, -116, 80, -6, -17, -58, -99, -37, -31, 12, 51, 19, 1, -9, -12,
                68, -111, -117, 25, 58, 111, 77, -127, -66, -64, -34, 20, 59, -64, -29, -2, 90, -100, -115, 30, 16, 114,
                -68, 61, 29, 40, 89, -112, -73, 25, 35, 120, -105, -67, -32, -43, -70, -84, 120, -55, 69, 43, -124, 106,
                -92, 18, -110, 114, -50, 111, 25, -3, 10, 17, -75, 13, 127, -84, 106, 90, -66, 84, -75, 84, 53, -89,
                -75, 92, -3, -40, -61, 119, 49, -117, 30, 49, 68, -59, 88, 74, -119, -34, 1, -83, -7, -48, 124, -124,
                -23, 16, 88, -118, 121, 54, -53, 1, 44, 32, 81, 19, 25, -115, -43, -32, -64, -67, -120, -110, -101, 121,
                -2, 2
            };

            sbyte[] secondPayload = new sbyte[] {
                -86, 86, 42, 46, 77, 78, 78, 45, 6, 26, 83, 82, 84, -102, -86, 3, -28, 38, 21, 39, 23, 101, 38, -91, 2,
                -51, -51, 47, 74, 73, 45, 114, -54, -49, -49, -10, 49, -78, -118, 112, 10, 9, 13, 118, 1, -102, 84,
                -108, 90, 88, 10, 116, 27, -56, -84, 124, -112, -13, 16, 26, 116, -108, 18, -117, -46, -127, 6, 69, 99,
                -45, 24, 91, 91, 11, 0
            };

            var parameters = new Dictionary <string, string>()
            {
                { ClientNoContext, null }
            };

            var extension = handshaker.HandshakeExtension(
                new WebSocketExtensionData(PerMessageDeflateExtension, parameters));

            Assert.NotNull(extension);

            var decoderChannel = new EmbeddedChannel(extension.NewExtensionDecoder());

            Assert.True(
                decoderChannel.WriteInbound(new TextWebSocketFrame(true, WebSocketRsv.Rsv1, Unpooled.CopiedBuffer(firstPayload.Select(_ => (byte)_).ToArray()))));
            TextWebSocketFrame firstFrameDecompressed = decoderChannel.ReadInbound <TextWebSocketFrame>();

            Assert.True(
                decoderChannel.WriteInbound(new TextWebSocketFrame(true, WebSocketRsv.Rsv1, Unpooled.CopiedBuffer(secondPayload.Select(_ => (byte)_).ToArray()))));
            TextWebSocketFrame secondFrameDecompressed = decoderChannel.ReadInbound <TextWebSocketFrame>();

            Assert.NotNull(firstFrameDecompressed);
            Assert.NotNull(firstFrameDecompressed.Content);
            //Assert.True(firstFrameDecompressed instanceof TextWebSocketFrame);
            Assert.Equal(firstFrameDecompressed.Text(),
                         "{\"info\":\"Welcome to the BitMEX Realtime API.\",\"version\"" +
                         ":\"2018-10-02T22:53:23.000Z\",\"timestamp\":\"2018-10-15T06:43:40.437Z\"," +
                         "\"docs\":\"https://www.bitmex.com/app/wsAPI\",\"limit\":{\"remaining\":39}}");
            Assert.True(firstFrameDecompressed.Release());

            Assert.NotNull(secondFrameDecompressed);
            Assert.NotNull(secondFrameDecompressed.Content);
            //Assert.True(secondFrameDecompressed instanceof TextWebSocketFrame);
            Assert.Equal(secondFrameDecompressed.Text(),
                         "{\"success\":true,\"subscribe\":\"orderBookL2:XBTUSD\"," +
                         "\"request\":{\"op\":\"subscribe\",\"args\":[\"orderBookL2:XBTUSD\"]}}");
            Assert.True(secondFrameDecompressed.Release());

            Assert.False(decoderChannel.Finish());
        }
Example #20
0
        protected internal override void Encode(IChannelHandlerContext ctx, WebSocketFrame msg, List <object> output)
        {
            if (this.encoder == null)
            {
                this.encoder = new EmbeddedChannel(
                    ZlibCodecFactory.NewZlibEncoder(
                        ZlibWrapper.None,
                        this.compressionLevel,
                        this.windowSize,
                        8));
            }

            this.encoder.WriteOutbound(msg.Content.Retain());

            CompositeByteBuffer fullCompressedContent = ctx.Allocator.CompositeBuffer();

            for (;;)
            {
                var partCompressedContent = this.encoder.ReadOutbound <IByteBuffer>();
                if (partCompressedContent == null)
                {
                    break;
                }

                if (!partCompressedContent.IsReadable())
                {
                    partCompressedContent.Release();
                    continue;
                }

                fullCompressedContent.AddComponent(true, partCompressedContent);
            }

            if (fullCompressedContent.NumComponents <= 0)
            {
                fullCompressedContent.Release();
                throw new CodecException("cannot read compressed buffer");
            }

            if (msg.IsFinalFragment && this.noContext)
            {
                this.Cleanup();
            }

            IByteBuffer compressedContent;

            if (this.RemoveFrameTail(msg))
            {
                int realLength = fullCompressedContent.ReadableBytes - FrameTail.Length;
                compressedContent = fullCompressedContent.Slice(0, realLength);
            }
            else
            {
                compressedContent = fullCompressedContent;
            }

            WebSocketFrame outMsg;

            if (msg is TextWebSocketFrame)
            {
                outMsg = new TextWebSocketFrame(msg.IsFinalFragment, this.Rsv(msg), compressedContent);
            }
            else if (msg is BinaryWebSocketFrame)
            {
                outMsg = new BinaryWebSocketFrame(msg.IsFinalFragment, this.Rsv(msg), compressedContent);
            }
            else if (msg is ContinuationWebSocketFrame)
            {
                outMsg = new ContinuationWebSocketFrame(msg.IsFinalFragment, this.Rsv(msg), compressedContent);
            }
            else
            {
                throw new CodecException($"unexpected frame type: {msg.GetType().Name}");
            }

            output.Add(outMsg);
        }
        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());
        }
 public async Task SendTextAsync(string text)
 {
     var frame = new TextWebSocketFrame(text);
     await _channel.WriteAndFlushAsync(frame);
 }