Exemplo n.º 1
0
        public void TestTextFrameMasking()
        {
            WebSocketFrame frame = WebSocketFrame.CreateTextFrame("this is some really great text!", true, false, true);

            MemoryStream stream = new MemoryStream();

            frame.Write(stream, true);
            stream.Position = 0;

            WebSocketFrame readFrame = WebSocketFrame.ParseFrame(stream);

            Assert.AreEqual(frame.DataAsString, readFrame.DataAsString);
        }
        public void TestEchoWithMaskWithSsl()
        {
            ObjectPool <byte[]> pool = new ObjectPool <byte[]>(() => { return(new byte[1024]); });

            WebSocketEchoServer server = new WebSocketEchoServer(pool);

            try
            {
                server.Start(true);

                BlockingCollection <object> blockingCollection = new BlockingCollection <object>();

                ClientSockNetChannel client = (ClientSockNetChannel)SockNetClient.Create(server.Endpoint, ClientSockNetChannel.DefaultNoDelay, ClientSockNetChannel.DefaultTtl, pool)
                                              .AddModule(new WebSocketClientSockNetChannelModule("/", "localhost", (ISockNetChannel sockNetClient) => { blockingCollection.Add(true); }));

                client.ConnectWithTLS((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return(true); })
                .WaitForValue(TimeSpan.FromSeconds(5));

                object currentObject;

                Assert.IsTrue(blockingCollection.TryTake(out currentObject, DEFAULT_ASYNC_TIMEOUT));
                Assert.IsTrue((bool)currentObject);

                client.Pipe.AddIncomingLast <WebSocketFrame>((ISockNetChannel sockNetClient, ref WebSocketFrame data) => { blockingCollection.Add(data); });

                client.Send(WebSocketFrame.CreateTextFrame("some test", true));

                Assert.IsTrue(blockingCollection.TryTake(out currentObject, DEFAULT_ASYNC_TIMEOUT));
                Assert.IsTrue(currentObject is WebSocketFrame);

                Assert.AreEqual("some test", ((WebSocketFrame)currentObject).DataAsString);

                Console.WriteLine("Got response: \n" + ((WebSocketFrame)currentObject).DataAsString);

                client.Disconnect().WaitForValue(TimeSpan.FromSeconds(5));
            }
            finally
            {
                server.Stop();
            }
        }
            /// <summary>
            /// Updates the local continuation.
            /// </summary>
            /// <param name="frame"></param>
            private void UpdateContinuation(ref WebSocketFrame continuationFrame, WebSocketFrame frame)
            {
                if (continuationFrame == null)
                {
                    continuationFrame = frame;  // set initial frame
                }
                else
                {
                    byte[] frameData = new byte[continuationFrame.Data.Length + frame.Data.Length];
                    Buffer.BlockCopy(continuationFrame.Data, 0, frameData, 0, continuationFrame.Data.Length);
                    Buffer.BlockCopy(frame.Data, 0, frameData, continuationFrame.Data.Length, frame.Data.Length);

                    switch (continuationFrame.Operation)
                    {
                    case WebSocketFrame.WebSocketFrameOperation.BinaryFrame:
                        continuationFrame = WebSocketFrame.CreateBinaryFrame(frameData, false, false);
                        break;

                    case WebSocketFrame.WebSocketFrameOperation.TextFrame:
                        continuationFrame = WebSocketFrame.CreateTextFrame(frameData, false, false);
                        break;
                    }
                }
            }
        public void TestIncompleteBufferParsing()
        {
            ObjectPool <byte[]> pool = new ObjectPool <byte[]>(() => { return(new byte[1024]); });

            WebSocketEchoServer server = new WebSocketEchoServer(pool);

            try
            {
                server.Start();

                BlockingCollection <object> blockingCollection = new BlockingCollection <object>();

                ClientSockNetChannel client = (ClientSockNetChannel)SockNetClient.Create(server.Endpoint, ClientSockNetChannel.DefaultNoDelay, ClientSockNetChannel.DefaultTtl, pool)
                                              .AddModule(new WebSocketClientSockNetChannelModule("/", "localhost", (ISockNetChannel sockNetClient) => { blockingCollection.Add(true); }));

                client.Connect().WaitForValue(TimeSpan.FromSeconds(5));

                object currentObject;

                Assert.IsTrue(blockingCollection.TryTake(out currentObject, DEFAULT_ASYNC_TIMEOUT));
                Assert.IsTrue((bool)currentObject);

                client.Pipe.AddIncomingLast <WebSocketFrame>((ISockNetChannel sockNetClient, ref WebSocketFrame data) => { blockingCollection.Add(data); });

                string body1 = new string('A', 4913) + "X";

                WebSocketFrame frame1 = WebSocketFrame.CreateTextFrame(
                    "STS/1.0 200 OK" + "\r\n" +
                    "s:7R" + "\r\n" +
                    "n:bytes 0-4915/5000" + "\r\n" +
                    "l:4916" + "\r\n" +
                    "" + "\r\n" +
                    body1 + "\r\n",
                    false);
                client.Send(frame1);

                string body2 = new string('B', 81) + "Y";

                WebSocketFrame frame2 = WebSocketFrame.CreateTextFrame(
                    "STS/1.0 200 OK" + "\r\n" +
                    "s:7R" + "\r\n" +
                    "n:bytes 4916-4999/5000" + "\r\n" +
                    "l:84" + "\r\n" +
                    "" + "\r\n" +
                    body2 + "\r\n",
                    false);

                client.Send(frame2);

                Assert.IsTrue(blockingCollection.TryTake(out currentObject, DEFAULT_ASYNC_TIMEOUT));
                Assert.IsTrue(currentObject is WebSocketFrame);

                Assert.AreEqual(frame1.DataAsString, ((WebSocketFrame)currentObject).DataAsString);

                Console.WriteLine("Got response: \n" + ((WebSocketFrame)currentObject).DataAsString);

                Assert.IsTrue(blockingCollection.TryTake(out currentObject, DEFAULT_ASYNC_TIMEOUT));
                Assert.IsTrue(currentObject is WebSocketFrame);

                Assert.AreEqual(frame2.DataAsString, ((WebSocketFrame)currentObject).DataAsString);

                Console.WriteLine("Got response: \n" + ((WebSocketFrame)currentObject).DataAsString);

                client.Disconnect().WaitForValue(TimeSpan.FromSeconds(5));
            }
            finally
            {
                server.Stop();
            }
        }
            public void Start(bool isTls = false, bool doContinuations = false)
            {
                server = SockNetServer.Create(GetLocalIpAddress(), 0, ServerSockNetChannel.DefaultBacklog, pool);

                try
                {
                    server.AddModule(new WebSocketServerSockNetChannelModule("/", "localhost"));

                    if (isTls)
                    {
                        byte[] rawCert = CertificateUtil.CreateSelfSignCertificatePfx("CN=\"test\"; C=\"USA\"", DateTime.Today.AddDays(-10), DateTime.Today.AddDays(+10));

                        server.BindWithTLS(new X509Certificate2(rawCert),
                                           (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return(true); }).WaitForValue(TimeSpan.FromSeconds(5));
                    }
                    else
                    {
                        server.Bind().WaitForValue(TimeSpan.FromSeconds(5));
                    }

                    Assert.IsTrue(server.IsActive);

                    server.Pipe.AddIncomingLast <WebSocketFrame>((ISockNetChannel channel, ref WebSocketFrame data) =>
                    {
                        if (doContinuations)
                        {
                            int perFrameSize = data.Data.Length / 3;

                            for (int i = 0; i < 3; i++)
                            {
                                bool isDone = false;
                                byte[] rawData;

                                if (i + 1 < 3)
                                {
                                    rawData = new byte[perFrameSize];
                                    isDone  = false;
                                }
                                else
                                {
                                    rawData = new byte[data.Data.Length - (perFrameSize * 2)];
                                    isDone  = true;
                                }

                                Buffer.BlockCopy(data.Data, i * perFrameSize, rawData, 0, rawData.Length);

                                if (data.Operation == WebSocketFrame.WebSocketFrameOperation.BinaryFrame)
                                {
                                    channel.Send(WebSocketFrame.CreateBinaryFrame(rawData, true, i != 0, isDone));
                                }
                                else
                                {
                                    channel.Send(WebSocketFrame.CreateTextFrame(rawData, true, i != 0, isDone));
                                }
                            }
                        }
                        else
                        {
                            channel.Send(data);
                        }
                    });
                }
                catch (Exception)
                {
                    Stop();
                }
            }
        public void TestContinuation()
        {
            ObjectPool <byte[]> pool = new ObjectPool <byte[]>(() => { return(new byte[1024]); });

            DummySockNetChannel channel = new DummySockNetChannel()
            {
                State      = null,
                IsActive   = true,
                BufferPool = pool
            };

            channel.Pipe = new SockNetChannelPipe(channel);

            WebSocketClientSockNetChannelModule module = new WebSocketClientSockNetChannelModule("/test", "test", null);

            channel.AddModule(module);
            channel.Connect();

            object sent = null;

            channel.outgoing.TryTake(out sent, 5000);
            Assert.IsTrue(sent is HttpRequest);

            HttpRequest request = (HttpRequest)sent;

            HttpResponse handshakeResponse = new HttpResponse(channel.BufferPool)
            {
                Code = "200", Reason = "OK", Version = "HTTP/1.1"
            };

            handshakeResponse.Header[WebSocketUtil.WebSocketAcceptHeader] = WebSocketUtil.GenerateAccept(request.Header[WebSocketUtil.WebSocketKeyHeader]);
            object receiveResponse = handshakeResponse;

            channel.Receive(ref receiveResponse);

            WebSocketFrame continuation1 = WebSocketFrame.CreateTextFrame("This ", false, false, false);
            ChunkedBuffer  buffer        = ToBuffer(continuation1);

            receiveResponse = buffer;
            channel.Receive(ref receiveResponse);
            buffer.Close();

            Assert.IsTrue(receiveResponse is ChunkedBuffer);

            WebSocketFrame continuation2 = WebSocketFrame.CreateTextFrame("is ", false, true, false);

            buffer          = ToBuffer(continuation2);
            receiveResponse = buffer;
            channel.Receive(ref receiveResponse);
            buffer.Close();

            Assert.IsTrue(receiveResponse is ChunkedBuffer);

            WebSocketFrame continuation3 = WebSocketFrame.CreateTextFrame("awesome!", false, true, true);

            buffer          = ToBuffer(continuation3);
            receiveResponse = buffer;
            channel.Receive(ref receiveResponse);
            buffer.Close();

            Assert.IsTrue(receiveResponse is WebSocketFrame);
            Assert.AreEqual("This is awesome!", ((WebSocketFrame)receiveResponse).DataAsString);

            Console.WriteLine("Pool stats: " + pool.ObjectsInPool + "/" + pool.TotalNumberOfObjects);
        }