public WebsocketClientWrapper(Uri endpoint, IMessageHandler messageHandler, IMessageEncoder encoder)
        {
            this.Endpoint       = endpoint;
            this.messageHandler = messageHandler;
            this.encoder        = encoder;
            const int bufferSize     = 1024 * 8;         // 8KiB
            const int bufferPoolSize = 100 * bufferSize; // 800KiB pool

            this.options = new WebSocketListenerOptions
            {
                SendBufferSize = bufferSize,
                BufferManager  = BufferManager.CreateBufferManager(bufferPoolSize, bufferSize),
                PingMode       = PingMode.LatencyControl,
                Logger         = new LoggerAdapter(Logger)
                {
                    IsDebugEnabled   = Logger.IsEnabled(LogLevel.Trace),
                    IsWarningEnabled = true,
                    IsErrorEnabled   = true
                },
            };
            var rfc6455 = new WebSocketFactoryRfc6455();

            rfc6455.MessageExtensions.Add(new WebSocketDeflateExtension());
            this.options.Standards.Add(rfc6455);
        }
Example #2
0
        public WebSocketEventListener(IPEndPoint endpoint, WebSocketListenerOptions options)
        {
            _listener = new WebSocketListener(endpoint, options);
            var rfc6455 = new WebSocketFactoryRfc6455(_listener);

            _listener.Standards.RegisterStandard(rfc6455);
        }
Example #3
0
        public void IndicateANonWebSocketConnection()
        {
            var extension = new Mock <IWebSocketMessageExtension>();

            extension.Setup(x => x.Name).Returns("test-extension");
            var ext = new WebSocketExtension("test-extension", new List <WebSocketExtensionOption>(new[]
            {
                new WebSocketExtensionOption("optionA")
            }));
            IWebSocketMessageExtensionContext ctx;

            extension.Setup(x => x.TryNegotiate(It.IsAny <WebSocketHttpRequest>(), out ext, out ctx))
            .Returns(true);

            var factory = new WebSocketFactoryRfc6455();

            factory.MessageExtensions.Add(extension.Object);
            var factories = new WebSocketFactoryCollection();

            factories.Add(factory);
            var handshaker = new WebSocketHandshaker(factories, new WebSocketListenerOptions
            {
                Logger       = this.logger,
                SubProtocols = new[]
                {
                    "superchat"
                }
            });

            using (var connectionInput = new MemoryStream())
                using (var connectionOutput = new MemoryStream())
                    using (var connection = new DummyNetworkConnection(connectionInput, connectionOutput))
                    {
                        using (var sw = new StreamWriter(connectionInput, Encoding.ASCII, 1024, true))
                        {
                            sw.WriteLine(@"GET /chat HTTP/1.1");
                            sw.WriteLine(@"Host: server.example.com");
                        }

                        connectionInput.Seek(0, SeekOrigin.Begin);

                        var result = handshaker.HandshakeAsync(connection).Result;
                        Assert.NotNull(result);
                        Assert.False((bool)result.IsWebSocketRequest);
                        Assert.False((bool)result.IsVersionSupported);

                        connectionOutput.Seek(0, SeekOrigin.Begin);

                        var sb = new StringBuilder();
                        sb.AppendLine(@"HTTP/1.1 400 Bad Request");
                        sb.AppendLine(@"Connection: close");
                        sb.AppendLine();

                        using (var sr = new StreamReader(connectionOutput))
                        {
                            var s = sr.ReadToEnd();
                            Assert.Equal(sb.ToString(), s);
                        }
                    }
        }
        public override void Open()
        {
            string[] protocols = SubProtocols;

            WebSocketListener listener = new WebSocketListener(mEndpoint, new WebSocketListenerOptions()
            {
                SubProtocols = protocols
            });

            WebSocketFactoryRfc6455 factory = new WebSocketFactoryRfc6455(listener);

            if (mPerMessageDeflate)
            {
                factory.MessageExtensions.RegisterExtension(new WebSocketDeflateExtension());
            }

            listener.Standards.RegisterStandard(factory);

            if (mCertificate != null)
            {
                listener.ConnectionExtensions.RegisterExtension(new WebSocketSecureConnectionExtension(mCertificate));
            }

            listener.Start();

            mListener = listener;

            Task.Run(new Func <Task>(ListenAsync));
        }
 public WebSocketEventListener(IPEndPoint endpoint, WebSocketListenerOptions options)
 {
     _listener = new WebSocketListener(endpoint, options);
     var rfc6455 = new WebSocketFactoryRfc6455(_listener);
     rfc6455.MessageExtensions.RegisterExtension(new WebSocketDeflateExtension());
     _listener.Standards.RegisterStandard(rfc6455);
 }
Example #6
0
        public void WebSocketHandshaker_FailsWhenBadRequest()
        {
            var extension = new Mock <IWebSocketMessageExtension>();

            extension.Setup(x => x.Name).Returns("test-extension");
            WebSocketExtension ext = new WebSocketExtension("test-extension", new List <WebSocketExtensionOption>(new[] { new WebSocketExtensionOption()
                                                                                                                          {
                                                                                                                              ClientAvailableOption = false, Name = "optionA"
                                                                                                                          } }));
            IWebSocketMessageExtensionContext ctx;

            extension.Setup(x => x.TryNegotiate(It.IsAny <WebSocketHttpRequest>(), out ext, out ctx))
            .Returns(true);

            var factory = new WebSocketFactoryRfc6455();

            factory.MessageExtensions.RegisterExtension(extension.Object);
            var factories = new WebSocketFactoryCollection();

            factories.RegisterStandard(factory);
            WebSocketHandshaker handshaker = new WebSocketHandshaker(factories, new WebSocketListenerOptions()
            {
                SubProtocols = new[] { "superchat" }
            });

            using (var ms = new MemoryStream())
            {
                using (var sw = new StreamWriter(ms, Encoding.ASCII, 1024, true))
                {
                    sw.WriteLine(@"GET /chat HTTP/1.1");
                    sw.WriteLine(@"Host: server.example.com");
                    sw.WriteLine(@"Upgrade: websocket");
                    sw.WriteLine(@"Connection: Upgrade");
                    sw.WriteLine(@"Cookie: key=W9g/8FLW8RAFqSCWBvB9Ag==#5962c0ace89f4f780aa2a53febf2aae5;");
                    sw.WriteLine(@"Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==");
                    sw.WriteLine(@"Sec-WebSocket-Protoco");
                }

                var position = ms.Position;
                ms.Seek(0, SeekOrigin.Begin);

                var result = handshaker.HandshakeAsync(ms).Result;
                Assert.IsNotNull(result);
                Assert.IsFalse(result.IsWebSocketRequest);
                Assert.IsFalse(result.IsVersionSupported);
                ms.Seek(position, SeekOrigin.Begin);

                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"HTTP/1.1 400 Bad Request");
                sb.AppendLine();

                using (var sr = new StreamReader(ms))
                {
                    var s = sr.ReadToEnd();
                    Assert.AreEqual(sb.ToString(), s);
                }
            }
        }
 public WebSocketEventListener(List <IPEndPoint> endpoints, WebSocketListenerOptions options)
 {
     foreach (var endpoint in endpoints)
     {
         var listener = new WebSocketListener(endpoint, options);
         var rfc6455  = new WebSocketFactoryRfc6455(listener);
         listener.Standards.RegisterStandard(rfc6455);
         _listeners.Add(listener);
     }
 }
        public WebSocketEventListener(IPEndPoint endpoint, WebSocketListenerOptions options)
        {
            _listener = new WebSocketListener(endpoint, options);
            var rfc6455 = new WebSocketFactoryRfc6455(_listener);

            rfc6455.MessageExtensions.RegisterExtension(new WebSocketDeflateExtension());
            _listener.Standards.RegisterStandard(rfc6455);
            //TODO ALLOW PEOPLE TO SET THEIR SERTS FOR WSS
            //_listener.ConnectionExtensions.RegisterExtension(new WebSocketSecureConnectionExtension(ca2));
        }
        public void WebSocketHandshaker_CanIndicateANonWebSocketConnection()
        {
            var extension = new Mock <IWebSocketMessageExtension>();

            extension.Setup(x => x.Name).Returns("test-extension");
            WebSocketExtension ext = new WebSocketExtension("test-extension", new List <WebSocketExtensionOption>(new[] { new WebSocketExtensionOption()
                                                                                                                          {
                                                                                                                              ClientAvailableOption = false, Name = "optionA"
                                                                                                                          } }));
            IWebSocketMessageExtensionContext ctx;

            extension.Setup(x => x.TryNegotiate(It.IsAny <WebSocketHttpRequest>(), out ext, out ctx))
            .Returns(true);

            var factory = new WebSocketFactoryRfc6455();

            factory.MessageExtensions.RegisterExtension(extension.Object);
            var factories = new WebSocketFactoryCollection();

            factories.RegisterStandard(factory);
            WebSocketHandshaker handshaker = new WebSocketHandshaker(factories, new WebSocketListenerOptions()
            {
                SubProtocols = new[] { "superchat" }
            });

            using (var ms = new MemoryStream())
            {
                using (var sw = new StreamWriter(ms, Encoding.ASCII, 1024, true))
                {
                    sw.WriteLine(@"GET /chat HTTP/1.1");
                    sw.WriteLine(@"Host: server.example.com");
                }

                var position = ms.Position;
                ms.Seek(0, SeekOrigin.Begin);

                var result = handshaker.HandshakeAsync(ms).Result;
                Assert.NotNull(result);
                Assert.False(result.IsWebSocketRequest);
                Assert.False(result.IsVersionSupported);
                ms.Seek(position, SeekOrigin.Begin);

                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"HTTP/1.1 400 Bad Request");
                sb.AppendLine();

                using (var sr = new StreamReader(ms))
                {
                    var s = sr.ReadToEnd();
                    Assert.AreEqual(sb.ToString(), s);
                }
            }
        }
Example #10
0
        protected Server(IPEndPoint endpoint)
        {
            var cancellation = new CancellationTokenSource();

            _token = cancellation;

            var server  = new WebSocketListener(endpoint);
            var rfc6455 = new WebSocketFactoryRfc6455();

            server.Standards.RegisterStandard(rfc6455);
            server.StartAsync(cancellation.Token).ConfigureAwait(false);

            Debug.WriteLine("Echo Server started at " + endpoint);

            var task = Task.Run(() => AcceptWebSocketClientsAsync(server, cancellation.Token), cancellation.Token);

            _runningTasks.Add(task);
        }
Example #11
0
        public override void Open()
        {
            string[] protocols = SubProtocols;

            WebSocketListenerOptions options = mOptions ?? new WebSocketListenerOptions();

            options.SubProtocols = protocols;

            WebSocketListener listener = new WebSocketListener(mEndpoint, options);

#if NETCORE
            WebSocketFactoryRfc6455 factory = new WebSocketFactoryRfc6455();
#else
            WebSocketFactoryRfc6455 factory = new WebSocketFactoryRfc6455(listener);
#endif
            if (mPerMessageDeflate)
            {
#if NETCORE
                listener.MessageExtensions.RegisterExtension(new WebSocketDeflateExtension());
#else
                factory.MessageExtensions.RegisterExtension(new WebSocketDeflateExtension());
#endif
            }

            listener.Standards.RegisterStandard(factory);

            if (mCertificate != null)
            {
                listener.ConnectionExtensions.RegisterExtension(new WebSocketSecureConnectionExtension(mCertificate));
            }

            mCancellationToken = new CancellationTokenSource();

#if NETCORE
            listener.StartAsync(mCancellationToken.Token);
#else
            listener.Start();
#endif

            mListener = listener;

            Task.Run(() => ListenAsync(mCancellationToken.Token));
        }
Example #12
0
        public WebSocketServer(IPEndPoint endpoint)
        {
            var options = new WebSocketListenerOptions
            {
                PingTimeout = TimeSpan.FromSeconds(30)
            };

            _cts         = new CancellationTokenSource();
            _listener    = new WebSocketListener(endpoint, options);
            _clientsSync = new object();
            _clients     = new List <TClient>();

            var rfc6455 = new WebSocketFactoryRfc6455(_listener);

            rfc6455.MessageExtensions.RegisterExtension(new WebSocketSharpDeflateExtension());
            _listener.Standards.RegisterStandard(rfc6455);

            _listener.Start();
            ListenAsync();
        }
Example #13
0
        public bool Bind(int retryCount)
        {
            var ok = false;

            do
            {
                try {
                    listener = new WebSocketListener(new IPEndPoint(IPAddress.Any, GlobalConst.LobbyServerPort + 1));
                    var rfc6455 = new WebSocketFactoryRfc6455(listener);
                    listener.Standards.RegisterStandard(rfc6455);
                    listener.Start();
                    ok = true;
                } catch (Exception ex) {
                    Trace.TraceError("Error binding:{0}", ex);
                    Thread.Sleep(1000);
                }
            } while (!ok && retryCount-- > 0);

            return(ok);
        }
Example #14
0
        public WebSocketQueueServer(IPEndPoint endpoint, ISystemInfo sysinfo, ILogger log)
        {
            _log          = log;
            _sysInfo      = sysinfo;
            _cancellation = new CancellationTokenSource();
            _serializator = new DefaultEventSerializator();

            Queue = ServiceBusFactory.New(sbc =>
            {
                sbc.UseBinarySerializer();
                sbc.ReceiveFrom("loopback://localhost/queue");
            });

            _wsServer = new WebSocketListener(endpoint, new WebSocketListenerOptions
            {
                PingTimeout       = Timeout.InfiniteTimeSpan,
                OnHttpNegotiation = HttpNegotiation
            });
            var rfc6455 = new WebSocketFactoryRfc6455(_wsServer);

            _wsServer.Standards.RegisterStandard(rfc6455);
        }
Example #15
0
        private ClientConnection()
        {
            var rfc6455 = new WebSocketFactoryRfc6455();

            _server.Standards.RegisterStandard(rfc6455);
        }
Example #16
0
        public void NegotiateAnExtensionWithParameters()
        {
            var extension = new Mock <IWebSocketMessageExtension>();

            extension.Setup(x => x.Name).Returns("test-extension");
            var ext = new WebSocketExtension("test-extension", new List <WebSocketExtensionOption>(new[]
            {
                new WebSocketExtensionOption("optionA")
            }));
            IWebSocketMessageExtensionContext ctx;

            extension.Setup(x => x.TryNegotiate(It.IsAny <WebSocketHttpRequest>(), out ext, out ctx))
            .Returns(true);

            var factory = new WebSocketFactoryRfc6455();

            factory.MessageExtensions.Add(extension.Object);
            var factories = new WebSocketFactoryCollection();

            factories.Add(factory);
            var handshaker = new WebSocketHandshaker(factories, new WebSocketListenerOptions
            {
                Logger       = this.logger,
                SubProtocols = new[]
                {
                    "superchat"
                }
            });

            using (var connectionInput = new MemoryStream())
                using (var connectionOutput = new MemoryStream())
                    using (var connection = new DummyNetworkConnection(connectionInput, connectionOutput))
                    {
                        using (var sw = new StreamWriter(connectionInput, Encoding.ASCII, 1024, true))
                        {
                            sw.WriteLine(@"GET /chat HTTP/1.1");
                            sw.WriteLine(@"Host: server.example.com");
                            sw.WriteLine(@"Upgrade: websocket");
                            sw.WriteLine(@"Connection: Upgrade");
                            sw.WriteLine(@"Cookie: key=W9g/8FLW8RAFqSCWBvB9Ag==#5962c0ace89f4f780aa2a53febf2aae5;");
                            sw.WriteLine(@"Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==");
                            sw.WriteLine(@"Sec-WebSocket-Protocol: chat, superchat");
                            sw.WriteLine(@"Sec-WebSocket-Extensions: test-extension;optionA");
                            sw.WriteLine(@"Sec-WebSocket-Version: 13");
                            sw.WriteLine(@"Origin: http://example.com");
                        }

                        connectionInput.Seek(0, SeekOrigin.Begin);

                        var result = handshaker.HandshakeAsync(connection).Result;
                        Assert.NotNull(result);
                        Assert.True((bool)result.IsWebSocketRequest);
                        Assert.Equal(new Uri("http://example.com"), new Uri(result.Request.Headers[RequestHeader.Origin]));
                        Assert.Equal((string)"superchat", (string)result.Response.Headers[ResponseHeader.WebSocketProtocol]);

                        connectionOutput.Seek(0, SeekOrigin.Begin);

                        var sb = new StringBuilder();
                        sb.AppendLine(@"HTTP/1.1 101 Switching Protocols");
                        sb.AppendLine(@"Upgrade: websocket");
                        sb.AppendLine(@"Connection: Upgrade");
                        sb.AppendLine(@"Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=");
                        sb.AppendLine(@"Sec-WebSocket-Protocol: superchat");
                        sb.AppendLine(@"Sec-WebSocket-Extensions: test-extension;optionA");
                        sb.AppendLine();

                        using (var sr = new StreamReader(connectionOutput))
                        {
                            var s = sr.ReadToEnd();
                            Assert.Equal(sb.ToString(), s);
                        }
                    }
        }
Example #17
0
        public void WebSocketHandshaker_CanNegotiateAnExtension()
        {
            var extension = new Mock <IWebSocketMessageExtension>();

            extension.Setup(x => x.Name).Returns("test-extension");
            WebSocketExtension ext = new WebSocketExtension("test-extension");
            IWebSocketMessageExtensionContext ctx;

            extension.Setup(x => x.TryNegotiate(It.IsAny <WebSocketHttpRequest>(), out ext, out ctx))
            .Returns(true);

            var factory = new WebSocketFactoryRfc6455();

            factory.MessageExtensions.RegisterExtension(extension.Object);
            var factories = new WebSocketFactoryCollection();

            factories.RegisterStandard(factory);
            WebSocketHandshaker handshaker = new WebSocketHandshaker(factories, new WebSocketListenerOptions()
            {
                SubProtocols = new[] { "superchat" }
            });

            using (var ms = new MemoryStream())
            {
                using (var sw = new StreamWriter(ms, Encoding.ASCII, 1024, true))
                {
                    sw.WriteLine(@"GET /chat HTTP/1.1");
                    sw.WriteLine(@"Host: server.example.com");
                    sw.WriteLine(@"Upgrade: websocket");
                    sw.WriteLine(@"Connection: Upgrade");
                    sw.WriteLine(@"Cookie: key=W9g/8FLW8RAFqSCWBvB9Ag==#5962c0ace89f4f780aa2a53febf2aae5;");
                    sw.WriteLine(@"Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==");
                    sw.WriteLine(@"Sec-WebSocket-Protocol: chat, superchat");
                    sw.WriteLine(@"Sec-WebSocket-Extensions: test-extension");
                    sw.WriteLine(@"Sec-WebSocket-Version: 13");
                    sw.WriteLine(@"Origin: http://example.com");
                }

                var position = ms.Position;
                ms.Seek(0, SeekOrigin.Begin);

                var result = handshaker.HandshakeAsync(ms).Result;
                Assert.IsNotNull(result);
                Assert.IsTrue(result.IsWebSocketRequest);
                Assert.AreEqual(new Uri("http://example.com"), result.Request.Headers.Origin);
                Assert.AreEqual("superchat", result.Response.WebSocketProtocol);

                ms.Seek(position, SeekOrigin.Begin);

                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"HTTP/1.1 101 Switching Protocols");
                sb.AppendLine(@"Upgrade: websocket");
                sb.AppendLine(@"Connection: Upgrade");
                sb.AppendLine(@"Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=");
                sb.AppendLine(@"Sec-WebSocket-Protocol: superchat");
                sb.AppendLine(@"Sec-WebSocket-Extensions: test-extension");
                sb.AppendLine();

                using (var sr = new StreamReader(ms))
                {
                    var s = sr.ReadToEnd();
                    Assert.AreEqual(sb.ToString(), s);
                }
            }
        }
Example #18
0
        static void Main(string[] args)
        {
            int port = args.Length > 0 ? int.Parse(args[0]) : 80;


            // reseting peformance counter
            PerformanceCounters.Connected     = 0;
            PerformanceCounters.Accepted      = 0;
            PerformanceCounters.Authenticated = 0;

            /* opening TLS certificate
             * X509Certificate2 certificate = null;
             * X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
             * store.Open(OpenFlags.ReadOnly);
             * if (store.Certificates.Count > 0)
             * {
             *  certificate = store.Certificates.Cast<X509Certificate2>().FirstOrDefault(cert => cert.Issuer.Contains("CN=stef-org")) ?? store.Certificates[0];
             * }
             * store.Close();*/

            CancellationTokenSource cancellation = new CancellationTokenSource();

            // local endpoint
            var endpoint = new IPEndPoint(IPAddress.Any, port);

            // starting the server
            const int maxClient = 10000;

            Console.WriteLine("maxClient = " + maxClient);
            var server = new WebSocketListener(endpoint, new WebSocketListenerOptions
            {
                SubProtocols             = new[] { "text" },
                PingTimeout              = TimeSpan.FromSeconds(500),
                NegotiationTimeout       = TimeSpan.FromSeconds(500),
                ParallelNegotiations     = 256,
                NegotiationQueueCapacity = 256,
                TcpBacklog    = 1000,
                BufferManager = BufferManager.CreateBufferManager((8192 + 1024) * maxClient, 8192 + 1024)
            });

            var rfc6455 = new WebSocketFactoryRfc6455(server);

            // adding the deflate extension
            rfc6455.MessageExtensions.RegisterExtension(new WebSocketDeflateExtension());
            server.Standards.RegisterStandard(rfc6455);

            /* adding the WSS extension (if possible)
             * if (certificate != null)
             * {
             *  server.ConnectionExtensions.RegisterExtension(new WebSocketSecureConnectionExtension(certificate));
             * }*/

            server.Start();

            Log("Echo Server started at " + endpoint);

            var acceptingTask = Task.Run(() => AcceptWebSocketClients(server, cancellation.Token));

            Console.WriteLine("Press key to stop");

            Console.ReadKey(true);
            Log("Server stopping");
            server.Stop();
            cancellation.Cancel();
            acceptingTask.Wait();

            Console.ReadKey(true);
        }