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));
 }
Esempio n. 2
0
 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);
     }
 }
Esempio n. 3
0
 public WSSessionManager(
     IPEndPoint endpoint, 
     CommandProcessorJson commandprocessor,
     IFormatter formatter)
     : base (commandprocessor, formatter)
 {
     listener = new WebSocketListener(endpoint);
     WebSocketFactoryRfc6455 standard = new WebSocketFactoryRfc6455(listener);
     listener.Standards.RegisterStandard(standard);
 }
        public static WebSocketFactoryCollection RegisterRfc6455(this WebSocketFactoryCollection collection, Action <WebSocketFactoryRfc6455> configure = null)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            var factory = new WebSocketFactoryRfc6455();

            configure?.Invoke(factory);

            collection.Add(factory);

            return(collection);
        }
        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;
        }
Esempio n. 6
0
        private static void StartWebSocketServer()
        {
            var cancellation = new CancellationTokenSource();

            var endpoint = new IPEndPoint(IPAddress.Any, 8005);
            var server = new WebSocketListener(endpoint);
            var rfc6455 = new WebSocketFactoryRfc6455(server);
            server.Standards.RegisterStandard(rfc6455);
            server.Start();

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

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

            Console.ReadKey(true);
            Log("Server stoping");
            cancellation.Cancel();
            task.Wait(cancellation.Token);
            Console.ReadKey(true);
        }
Esempio n. 7
0
        public static void runSocketServer()
        {
            CancellationTokenSource cancellation = new CancellationTokenSource();

            var endpoint             = new IPEndPoint(IPAddress.Loopback, 8005);
            WebSocketListener server = new WebSocketListener(endpoint);
            var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(server);

            server.Standards.RegisterStandard(rfc6455);
            server.Start();

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

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

            Console.ReadKey(true);
            Log("Server stoping");
            cancellation.Cancel();
            task.Wait();
        }
        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);
        }
        public void WebSocketHandshaker_CanIndicateANonSupportedVersion()
        {
            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-Protocol: chat, superchat");
                    sw.WriteLine(@"Sec-WebSocket-Extensions: test-extension;optionA");
                    sw.WriteLine(@"Sec-WebSocket-Version: 14");
                    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.IsFalse(result.IsVersionSupported);
                ms.Seek(position, SeekOrigin.Begin);

                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"HTTP/1.1 426 Upgrade Required");
                sb.AppendLine(@"Sec-WebSocket-Version: 13");
                sb.AppendLine();

                using (var sr = new StreamReader(ms))
                {
                    var s = sr.ReadToEnd();
                    Assert.AreEqual(sb.ToString(), s);
                }
            }
        }
        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.IsNotNull(result);
                Assert.IsFalse(result.IsWebSocketRequest);
                Assert.IsFalse(result.IsVersionSupported);
                ms.Seek(position, SeekOrigin.Begin);

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

                using (var sr = new StreamReader(ms))
                {
                    var s = sr.ReadToEnd();
                    Assert.AreEqual(sb.ToString(), s);
                }
            }
        }
Esempio n. 11
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);
        }
        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.NotNull(result);
                Assert.True(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);
                }
            }
        }