Example #1
0
        static void Main(String[] args)
        {
            CancellationTokenSource cancellation = new CancellationTokenSource();

            var endpoint = new IPEndPoint(IPAddress.Any, 8001);
            WebSocketListener server = new WebSocketListener(endpoint, new WebSocketListenerOptions() { SubProtocols = new[] {"chat"} });
            var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(server);
            rfc6455.MessageExtensions.RegisterExtension(new WebSocketDeflateExtension());
            server.Standards.RegisterStandard(rfc6455);
            server.Start();

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

            var chatSessionObserver = new ChatSessionsObserver(new ChatRoomManager());

            Observable.FromAsync(server.AcceptWebSocketAsync)
                      .Select(ws => new ChatSession(ws) 
                              { 
                                  In = Observable.FromAsync<dynamic>(ws.ReadDynamicAsync)
                                                 .DoWhile(() => ws.IsConnected)
                                                 .Where(msg => msg != null), 
                    
                                  Out = Observer.Create<dynamic>(ws.WriteDynamic) 
                              })
                      .DoWhile(() => server.IsStarted && !cancellation.IsCancellationRequested)
                      .Subscribe(chatSessionObserver);
         
            Console.ReadKey(true);
            Log("Server stoping");
            cancellation.Cancel();
            Console.ReadKey(true);
        }
		public void BasicRoundTrip()
		{
			var serializer = new JsonCommonSerializer();

			var port = new Random().Next(6000, 60000);

			var options = new WebSocketListenerOptions();
			options.SubProtocols = new[] { "SignalR" };
			var listener = new WebSocketListener(new IPEndPoint(IPAddress.Loopback, port), options);
			var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(listener);
			listener.Standards.RegisterStandard(rfc6455);
			var serverTransport = listener.GenerateTransportSource();
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<IMyService>(new MyService());
			listener.Start();

			var client = new ClientWebSocket();
			client.Options.AddSubProtocol("SignalR");
			var clientTransport = client.GenerateTransportSource();
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<IMyService>();
			client.ConnectAsync(new Uri("ws://localhost:" + port + "/"), CancellationToken.None).Wait();

			var result = proxy.Add(3, 4).Result;
			Assert.Equal(7, result);

			clientRouter.Dispose();
			clientTransport.Dispose();
			client.Dispose();

			serverRouter.Dispose();
			serverTransport.Dispose();
			listener.Dispose();
		}
 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));
 }
        static void Main(string[] args)
        {
            if (PerformanceCounters.CreatePerformanceCounters())
                return;

            // reseting peformance counter
            PerformanceCounters.Connected.RawValue = 0;

            // configuring logging
            log4net.Config.XmlConfigurator.Configure();
            _log.Info("Starting Echo Server");
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // opening TLS certificate
            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            store.Certificates.Count.ToString();
            var certificate = store.Certificates[1];
            store.Close();
            
            CancellationTokenSource cancellation = new CancellationTokenSource();
            
            // local endpoint
            var endpoint = new IPEndPoint(IPAddress.Any, 8006);
            
            // starting the server
            WebSocketListener server = new WebSocketListener(endpoint, new WebSocketListenerOptions() 
            {
                SubProtocols = new []{"text"},
                PingTimeout = TimeSpan.FromSeconds(5),
                NegotiationTimeout = TimeSpan.FromSeconds(5),
                ParallelNegotiations = 16,
                NegotiationQueueCapacity = 256,
                TcpBacklog = 1000,
                BufferManager = BufferManager.CreateBufferManager((8192 + 1024)*1000, 8192 + 1024)
            });
            var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(server);
            // adding the deflate extension
            rfc6455.MessageExtensions.RegisterExtension(new WebSocketDeflateExtension());
            server.Standards.RegisterStandard(rfc6455);
            // adding the WSS extension
            server.ConnectionExtensions.RegisterExtension(new WebSocketSecureConnectionExtension(certificate));

            server.Start();

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

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

            Console.ReadKey(true);
            Log("Server stoping");

            cancellation.Cancel();
            acceptingTask.Wait();

            Console.ReadKey(true);
        }
 protected override void OnStop()
 {
     if (_listener != null)
     {
         try { _cancellation.Cancel(); }
         catch { }
         _listener.Dispose();
         _listener = null;
     }
 }
 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);
     }
 }
Example #7
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);
 }
        protected override void OnStart(string[] args)
        {
            _cancellation = new CancellationTokenSource();
            _listener = new WebSocketListener(new IPEndPoint(IPAddress.Any, _port));
            var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(_listener);
            _listener.Standards.RegisterStandard(rfc6455);

            var task = Task.Run(() => AcceptWebSocketClientsAsync(_listener, _cancellation.Token));

            _listener.Start();
        }
 private async Task AcceptWebSocketClientsAsync(WebSocketListener server, CancellationToken token)
 {
     while (!token.IsCancellationRequested)
     {
         try
         {
             var ws = await server.AcceptWebSocketAsync(token).ConfigureAwait(false);
             if (ws != null)
                 Task.Run(() => HandleConnectionAsync(ws, token));
         }
         catch (Exception aex)
         {
             Log("Error Accepting clients: " + aex.GetBaseException().Message);
         }
     }
     Log("Server Stop accepting clients");
 }
Example #10
0
 private async Task HandleListners(WebSocketListener listener)
 {
     while (listener.IsStarted)
     {
         try
         {
             var websocket = await listener.AcceptWebSocketAsync(CancellationToken.None)
                 .ConfigureAwait(false);
             if (websocket != null)
                 Task.Run(() => HandleWebSocketAsync(websocket));
         }
         catch (Exception ex)
         {
             OnError?.Invoke(null, ex);
         }
     }
 }
Example #11
0
        public void Start()
        {
            attackerQueue = new Queue<String>();
            defenderQueue = new Queue<String>();
            wsToIdDictionary = new Dictionary<WebSocket, String>();
            idToPlayerDictionary = new Dictionary<String, Player>();

            cancellation = new CancellationTokenSource();
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8005);
            server = new WebSocketListener(endpoint);
            var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(server);
            server.Standards.RegisterStandard(rfc6455);
            server.Start();

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

            var task = Task.Run(() => AcceptWebSocketClientsAsync(server, cancellation.Token));
        }
Example #12
0
        async Task AcceptWebSocketClientsAsync(WebSocketListener server, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                try
                {
                    var ws = await server.AcceptWebSocketAsync(token).ConfigureAwait(false);
                    Console.WriteLine("A new connection joined the server: " + ws.RemoteEndpoint);

                    if (ws != null)
                        Task.Run(() => HandleConnectionAsync(ws, token));
                }
                catch (Exception aex)
                {
                    Console.WriteLine("Error Accepting clients: " + aex.GetBaseException().Message);
                }
            }
            Console.WriteLine("Server Stop accepting clients");
        }
        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 static void Main (string[] args)
		{
			CancellationTokenSource cancellation = new CancellationTokenSource();

			var endpoint = new IPEndPoint(IPAddress.Any, 8005);
			WebSocketListener server = new WebSocketListener(endpoint, new WebSocketListenerOptions(){ SubProtocols = new []{"text"}});
			var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(server);
			server.Standards.RegisterStandard(rfc6455);
			server.Start();

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

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

			Console.ReadKey(true);
			Log("Server stoping");
			cancellation.Cancel();
			task.Wait();
			Console.ReadKey(true);
		}
Example #15
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);
        }
        public LogEntryDistributor(Int32 port, String ipAddressStart, Int32 maxConnectedClients, TimeSpan clientTimeout)
        {
            _maxConnectedClients = maxConnectedClients;
            _ipAddressStart = ipAddressStart;
            _listener = new WebSocketListener(new IPEndPoint(IPAddress.Any, port), new WebSocketListenerOptions
            {
                PingTimeout = clientTimeout
            });
            _listener.Standards.RegisterStandard(new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455());
            _cancel = new CancellationTokenSource();
            _block = new BufferBlock<LogEntry>(new DataflowBlockOptions() { CancellationToken = _cancel.Token });
            _connections = new List<WebSocketWrapper>();
            _serializer = new JsonSerializer();
            _semaphore = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);

            _commandHandlers = new[] { new FilterCommandHandler() };

            _listener.Start();
            Task.Run((Func<Task>)AcceptConnections);
            Task.Run((Func<Task>)ReceiveAndBroadcast);
        }
Example #17
0
        static async Task AcceptWebSocketClients(WebSocketListener server, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                try
                {
                    var ws = await server.AcceptWebSocketAsync(token).ConfigureAwait(false);
                    if (ws == null)
                        continue;

                    Task.Run(() => HandleConnectionAsync(ws, token));
                }
                catch (Exception aex)
                {
                    var ex = aex.GetBaseException();
                    _log.Error("AcceptWebSocketClients", ex);
                    Log("Error Accepting client: " + ex.GetType().Name +": " + ex.Message);
                }
            }
            Log("Server Stop accepting clients");
        }
        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 BasicRoundTrip()
		{
			var serializer = new JsonCommonSerializer();

			var port = new Random().Next(6000, 60000);

			var options = new WebSocketListenerOptions();
			options.SubProtocols = new[] { "SignalR" };
			var listener = new WebSocketListener(new IPEndPoint(IPAddress.Loopback, port), options);
			var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(listener);
			listener.Standards.RegisterStandard(rfc6455);
			var serverTransport = listener.GenerateTransportSource();
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<IMyService>(new MyService());
			listener.Start();

			var client = new WebSocket("ws://localhost:" + port + "/", "SignalR", WebSocket4Net.WebSocketVersion.Rfc6455);
			var clientTransport = client.GenerateTransportSource();
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<IMyService>();
			client.Open();

			while (client.State != WebSocket4Net.WebSocketState.Open)
				Thread.Sleep(10);

			var result = proxy.Add(3, 4).Result;
			Assert.Equal(7, result);

			clientRouter.Dispose();
			clientTransport.Dispose();
			client.Dispose();

			serverRouter.Dispose();
			serverTransport.Dispose();
			listener.Dispose();
		}
Example #20
0
 public WebSocketFactory(WebSocketListener listener)
 {
     MessageExtensions = new WebSocketMessageExtensionCollection(listener);
 }
 public WebSocketEventListener(IPEndPoint endpoint, WebSocketListenerOptions options)
 {
     _listener = new WebSocketListener(endpoint, options);
     _listener.Standards.RegisterStandard(new WebSocketFactoryRfc6455(_listener));
 }
 public WebSocketMessageExtensionCollection(WebSocketListener webSocketListener)
     : this()
 {
     _listener = webSocketListener;
 }
 public WebSocketFactory(WebSocketListener listener)
 {
     MessageExtensions = new WebSocketMessageExtensionCollection(listener);
 }
		public void Benchmark()
		{
			var serializer = new JsonCommonSerializer();

			var port = new Random().Next(6000, 60000);

			var options = new WebSocketListenerOptions();
			options.SubProtocols = new[] { "SignalR" };
			var listener = new WebSocketListener(new IPEndPoint(IPAddress.Loopback, port), options);
			var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(listener);
			listener.Standards.RegisterStandard(rfc6455);
			var serverTransport = listener.GenerateTransportSource();
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<ISumService>(new SumService());
			listener.Start();

			var client = new WebSocket("ws://localhost:" + port + "/", "SignalR", WebSocket4Net.WebSocketVersion.Rfc6455);
			var clientTransport = client.GenerateTransportSource();
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<ISumService>();
			client.Open();

			while (client.State != WebSocket4Net.WebSocketState.Open)
				Thread.Sleep(10);

			const int randCnt = 100;
			var rand = new Random(42);
			var randoms = new int[randCnt];
			for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);

			var sw = new Stopwatch();
			long timeFromClient = 0, timeToClient = 0;
			const int cnt = 1000;
			for (int j = 0; j < cnt; j++)
			{
				sw.Start();
				var sum = proxy.Sum(randoms).Result;
				sw.Stop();
				Assert.Equal(randoms.Sum(), sum);
				for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);
				var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result;
				timeFromClient += times.Item1;
				timeToClient += Stopwatch.GetTimestamp() - times.Item2;
			}

			_testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds);
			_testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10);
			_testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10);

			//sw.Reset();
			//var tree = new SumServiceTree();
			//SumServiceTree.FillTree(tree, rand, 2);
			//_testOutputHelper.WriteLine("Starting large message transfer.");
			//sw.Start();
			//var result = proxy.Increment(tree).Result;
			//sw.Stop();
			//Assert.Equal(tree.Leaf + 1, result.Leaf);
			//_testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds);

			clientRouter.Dispose();
			clientTransport.Dispose();
			client.Dispose();

			serverRouter.Dispose();
			serverTransport.Dispose();
			listener.Dispose();
		}
Example #25
0
 public WebSocketConnectionExtensionCollection(WebSocketListener webSocketListener)
     : this()
 {
     _listener = webSocketListener;
 }
 private async Task AcceptWebSocketClientsAsync(WebSocketListener server)
 {
     while (!_cancellation.IsCancellationRequested)
     {
         try
         {
             var ws = await server.AcceptWebSocketAsync(_cancellation.Token).ConfigureAwait(false);
             if (ws == null) continue;
             var handler = new WebSocketHandler(Queue, ws, _serializator, _log);
             Task.Run(() => handler.HandleConnectionAsync(_cancellation.Token));
         }
         catch (TaskCanceledException)
         {
         }
         catch (InvalidOperationException)
         {
         }
         catch (Exception aex)
         {
             _log.Error("Error Accepting clients", aex.GetBaseException());
         }
     }
     _log.Info("Server Stop accepting clients");
 }
Example #27
0
 public WebSocketFactoryCollection(WebSocketListener webSocketListener)
     : this()
 {
     _listener = webSocketListener;
 }
        public void Open()
        {
            IPAddress ipAddress = IPAddress.Any;
            if (_endPointUri.IsLoopback)
            {
                ipAddress = IPAddress.Loopback;
            }
            else if (!"0.0.0.0".Equals(_endPointUri.DnsSafeHost))
            {
                ipAddress = IOUtil.GetIPAddress(_endPointUri.DnsSafeHost);
            }

            var options = new WebSocketListenerOptions()
            {
                NegotiationQueueCapacity = 128,
                ParallelNegotiations = 16,
                PingTimeout = Timeout.InfiniteTimeSpan,
                SubProtocols = new[] {"v1.openicf.forgerock.org"},
                OnHttpNegotiation = (request, response) =>
                {
                    var authHeader = request.Headers["Authorization"];
                    if (authHeader != null)
                    {
                        var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);

                        // RFC 2617 sec 1.2, "scheme" name is case-insensitive
                        if (authHeaderVal.Scheme.Equals("basic",
                            StringComparison.OrdinalIgnoreCase) &&
                            authHeaderVal.Parameter != null)
                        {
                            var encoding = Encoding.GetEncoding("iso-8859-1");
                            var credentials = encoding.GetString(Convert.FromBase64String(authHeaderVal.Parameter));

                            int separator = credentials.IndexOf(':');
                            if (separator != -1)
                            {
                                string name = credentials.Substring(0, separator);
                                string password = credentials.Substring(separator + 1);

                                var pair = _validator.FindPrincipal(name);
                                if (null != pair)
                                {
                                    if (ClientAuthenticationValidator.Verify(pair.Second, password))
                                    {
                                        request.Items["ConnectionPrincipal"] = pair.First;
                                    }
                                    else
                                    {
                                        Trace.TraceWarning("Incorrect password - username: {0}", name);
                                        response.Status = HttpStatusCode.Forbidden;
                                    }
                                }
                                else
                                {
                                    Trace.TraceWarning("Unknown username: {0}", name);
                                    response.Status = HttpStatusCode.Forbidden;
                                }
                            }
                            else
                            {
                                Trace.TraceWarning("Invalid Basic Authorization : {0}", credentials);
                                response.Status = HttpStatusCode.BadRequest;
                            }
                        }
                        else
                        {
                            Trace.TraceWarning("Basic Authorization header expected but found{0}", authHeader);
                            response.Status = HttpStatusCode.BadRequest;
                        }
                    }
                    else
                    {
                        //401 + Realm
                        response.Status = HttpStatusCode.Unauthorized;
                    }
                }
            };
            _listener = new WebSocketListener(new IPEndPoint(ipAddress, _endPointUri.Port), options);

            bool useSsl = String.Equals("https", _endPointUri.Scheme, StringComparison.OrdinalIgnoreCase) ||
                          String.Equals("wss", _endPointUri.Scheme, StringComparison.OrdinalIgnoreCase);
            if (useSsl)
            {
                _listener.ConnectionExtensions.RegisterExtension(
                    new WebSocketSecureConnectionExtension(GetCertificate()));
            }

            var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(_listener);
            _listener.Standards.RegisterStandard(rfc6455);
            _listener.Start();
            Task.Run((Func<Task>) ListenAsync);
        }
		public WebSocketListenerTransportSource(WebSocketListener listener)
		{
			_listener = listener;
			ListenForSockets();
		}
Example #30
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);
        }
Example #31
0
        static async Task AcceptWebSocketClients(WebSocketListener server, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                try
                {
                    var ws = await server.AcceptWebSocketAsync(token).ConfigureAwait(false);
                    if (ws == null)
                        continue;

                    //int y = 0;

                    Interlocked.Increment(ref PerformanceCounters.Accepted);
                    Console.WriteLine("Accepted " + PerformanceCounters.Accepted);

                    //queue.Enqueue(new QueueItem { WebSocket = ws, TimeStamp = DateTime.Now});
                    //HandleConnectionAsync(ws, token);
                    //Task.Run(() => HandleConnectionAsync(ws, token));

                    Task.Factory.StartNew(() => HandleConnectionAsync(ws, token));
                }
                catch (Exception aex)
                {
                    var ex = aex.GetBaseException();
                    Log("Error AcceptWebSocketClients" + ex);
                    Log("Error Accepting client: " + ex.GetType().Name + ": " + ex.Message);
                }
            }

            Log("Server Stop accepting clients");
        }