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(); }
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 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(); }
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)); }
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; }
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); }
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); }
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(); }
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(); }
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 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); }