Esempio n. 1
0
        public void RestartListener()
        {
            Uri anAddress1 = new Uri("ws://127.0.0.1:8087/MyService1/");
            WebSocketListener aService1 = new WebSocketListener(anAddress1);

            Uri anAddress2 = new Uri("ws://127.0.0.1:8087/MyService2/");
            WebSocketListener aService2 = new WebSocketListener(anAddress2);

            try
            {
                // Start the first listener.
                aService1.StartListening(x => { });

                // Start the second listener.
                aService2.StartListening(x => { });

                aService2.StopListening();

                aService2.StartListening(x => { });
            }
            finally
            {
                aService1.StopListening();
                aService2.StopListening();
            }
        }
Esempio n. 2
0
        public void MaxAmountOfClients()
        {
            Uri anAddress = new Uri("ws://127.0.0.1:8087/MyService/");
            WebSocketListener aService = new WebSocketListener(anAddress);

            aService.MaxAmountOfClients = 2;

            // Client will connect with the query.
            WebSocketClient aClient1 = new WebSocketClient(anAddress);
            WebSocketClient aClient2 = new WebSocketClient(anAddress);
            WebSocketClient aClient3 = new WebSocketClient(anAddress);

            try
            {
                // Start listening.
                aService.StartListening(clientContext => { });

                aClient1.OpenConnection();
                aClient2.OpenConnection();

                // This opening shall fail with the exception.
                Assert.Throws <IOException>(() => aClient3.OpenConnection());
            }
            finally
            {
                aClient1.CloseConnection();
                aClient2.CloseConnection();
                aClient3.CloseConnection();
                aService.StopListening();
            }
        }
Esempio n. 3
0
 public void JoinLobby()
 {
     if (PlayerNameInputField.text.Length > 0)
     {
         if (GameCodeInputField.text.Length <= 0)
         {
             GameCodeInputField.text = "GAME";
         }
         addToActivityStream("Attempt to join lobby " + GameCodeInputField.text);
         Api.JoinLobby(GameCodeInputField.text, PlayerNameInputField.text, (resp) => {
             addToActivityStream("Joined lobby " + GameCodeInputField.text);
             WebSocketListener.Instance().StartListening(GameCodeInputField.text, PlayerNameInputField.text,
                                                         () => { addToActivityStream("Made websocket connection"); });
             GameCodeInputField.interactable   = false;
             PlayerNameInputField.interactable = false;
             CreateButton.interactable         = false;
             JoinButton.interactable           = false;
             ReadyButton.interactable          = true;
         });
     }
     else
     {
         addToActivityStream("Failed to join lobby, must have a player name");
     }
 }
        public void createReactiveWebSocketServer(IPAddress ip, int port)
        {
            var endpoint = new IPEndPoint(ip, port);

            server = new WebSocketListener(endpoint);
            setRFC6455ServerStandards();
        }
Esempio n. 5
0
        public WebSocketEventListener(IPEndPoint endpoint, WebSocketListenerOptions options)
        {
            _listener = new WebSocketListener(endpoint, options);
            var rfc6455 = new WebSocketFactoryRfc6455(_listener);

            _listener.Standards.RegisterStandard(rfc6455);
        }
Esempio n. 6
0
        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, 8005);

            // 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");
            server.Stop();
            cancellation.Cancel();
            acceptingTask.Wait();

            Console.ReadKey(true);
        }
Esempio n. 7
0
        private void Run(string[] args)
        {
            var host = ConfigurationManager.AppSettings["BroadcastServerHost"];
            var port = Convert.ToInt32(ConfigurationManager.AppSettings["BroadcastServerPort"]);

            CancellationTokenSource cancellation = new CancellationTokenSource();
            var endpoint             = new IPEndPoint(host.Trim().ToLower() == "*" ? IPAddress.Any : IPAddress.Parse(host), port);
            WebSocketListener server = new WebSocketListener(endpoint);
            var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(server);

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

            Console.WriteLine($"{this.GetType().Namespace} on host {endpoint.ToString()}");
            var task = Task.Run(() => AcceptWebSocketClientsAsync(server, cancellation.Token));

            Console.WriteLine("Press Ctrl-C to quit");
            var exitEvent = new ManualResetEvent(false);

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                exitEvent.Set();
            };
            exitEvent.WaitOne();

            // cancel socket server and wait for completion
            cancellation.Cancel();
            task.Wait();
        }
Esempio n. 8
0
        private async Task AcceptWebSocketClientsAsync(WebSocketListener server, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                try
                {
                    var ws = await server.AcceptWebSocketAsync(token).ConfigureAwait(false);

                    if (ws != null)
                    {
                        try
                        {
                            Task.Run(() => HandleConnectionAsync(ws, token));
                        }
                        finally
                        {
                        }
                    }
                }
                catch (Exception aex)
                {
                    Error("Error Accepting clients: " + aex.GetBaseException().Message);
                }
            }
            Log("Server Stop accepting clients");
        }
Esempio n. 9
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");
        }
Esempio n. 10
0
        public WebSocketServer(int port)
        {
            WebSocketListenerOptions opts = new WebSocketListenerOptions()
            {
                SubProtocols = new string[] { "text" },
                //NegotiationQueueCapacity = 128,
                ParallelNegotiations      = 16,
                HttpAuthenticationHandler = async(request, response) => {
                    await Task.Delay(0);             // To shut the f*****g IDE up

                    if (LiveMap.accessOrigin == "*") // If they're allowing anyone
                    {
                        return(true);
                    }

                    // Check if the origin is the same as the accessOrigin in CFG file
                    return(request.Headers["Origin"].Equals(LiveMap.accessOrigin, StringComparison.CurrentCultureIgnoreCase));
                }
            };

            opts.Standards.RegisterRfc6455();

            //opts.HttpAuthenticationHandler = OnHttpNegotiationDelegate;

            listener = new WebSocketListener(new System.Net.IPEndPoint(System.Net.IPAddress.Any, port), opts);

            LiveMap.Log(LiveMap.LogLevel.Basic, "Created websocket server");
        }
        private void Awake()
        {
            _websocketListener             = WebSocketListener.Platform;
            _websocketListener.NewMessage += this.OnNewMessage;

            try
            {
                var uri = new Uri(_uri);

                _websocketListener.Connect(
                    uri,
                    // success
                    () =>
                {
                    Debug.Log("Connected");
                },
                    // failure
                    () =>
                {
                    _websocketListener.Dispose();
                    _websocketListener = null;
                    Debug.LogError("Failed to connect");
                });
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        public static bool DestroyRoom(uint roomId, string reason = "")
        {
#if DEBUG
            Logger.Instance.Log("Destroying room " + roomId);
#endif
            if (rooms.Any(x => x.roomId == roomId))
            {
                BaseRoom room = rooms.First(x => x.roomId == roomId);
                room.StopRoom();
                WebSocketListener.DestroyRoom(room);

                if (string.IsNullOrEmpty(reason))
                {
                    reason = "Room destroyed!";
                }

                NetOutgoingMessage outMsg = HubListener.ListenerServer.CreateMessage();

                outMsg.Write((byte)CommandType.Disconnect);
                outMsg.Write(reason);

                room.BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered);
                rooms.Remove(room);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 13
0
        private static async Task StartServer()
        {
            Log.Print(LogType.Game, "Starting GameServer");
            WebSocketListener server = new WebSocketListener(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 6061));

            server.Standards.RegisterStandard(new WebSocketFactoryRfc6455());

            // Server doesnt start if i await StartAsync...
#pragma warning disable CS4014
            server.StartAsync();
#pragma warning restore CS4014

            Log.Print(LogType.Game, "Started GameServer on '0.0.0.0:6061'");

            while (true)
            {
                Log.Print(LogType.Game, "Waiting for clients to connect...");
                WebSocket socket = await server.AcceptWebSocketAsync(CancellationToken.None);

                Log.Print(LogType.Game, "Client connected");
                GameServerConnection newClient = new GameServerConnection(socket);
                ConnectedClients.Add(newClient);

                new Thread(newClient.HandleConnection).Start();
            }
        }
        public async Task BasicClientServerTest()
        {
            WebSocketListener server = new WebSocketListener(PORT);

            byte[] message = new byte[] { 100, 101, 102, 103 };

            server.Start();

            Task task = Task.Run(async() => {
                Stream socket = await server.AcceptWebSocketAsync();

                byte[] buffer = new byte[1024];
                int read      = await socket.ReadAsync(buffer, 0, buffer.Length);

                Assert.Equal(4, read);
                Assert.Equal(message, buffer.Take(4).ToArray());
            });

            Stream client = WebSocketStream.Connect($"ws://localhost:{PORT}");

            await client.WriteAsync(message, 0, message.Length);

            client.Dispose();
            server.Dispose();

            await task;
        }
Esempio n. 15
0
        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");
        }
Esempio n. 16
0
        private static async Task StartServer()
        {
            Log.Print(LogType.Lobby, "Starting LobbyServer");
            WebSocketListener server = new WebSocketListener(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6060));

            server.Standards.RegisterStandard(new WebSocketFactoryRfc6455());

            // Server doesnt start if i await StartAsync...
#pragma warning disable CS4014
            server.StartAsync();
#pragma warning restore CS4014

            Log.Print(LogType.Lobby, "Started LobbyServer on '0.0.0.0:6060'");
            LobbyQueueManager.GetInstance();
            while (true)
            {
                Log.Print(LogType.Lobby, "Waiting for clients to connect...");
                WebSocket socket = await server.AcceptWebSocketAsync(CancellationToken.None);

                Log.Print(LogType.Lobby, "Client connected");
                LobbyServerConnection newClient = new LobbyServerConnection(socket);
                newClient.OnDisconnect += NewClient_OnDisconnect;
                ConnectedClients.Add(newClient);
                new Thread(newClient.HandleConnection).Start();
            }
        }
Esempio n. 17
0
 public Server()
 {
     ws = new WebSocketListener(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080));
     ws.Standards.RegisterStandard(new WebSocketFactoryRfc6455());
     ws.StartAsync();
     GetNewUser();
 }
    void Start()
    {
        Api = FindObjectOfType <RestApi>();

        WebSocketListener.Instance().Subscribe(this);

        CardTray = FindObjectOfType <CardTrayBehaviour>();
        CardTray.OnSelected.AddListener(OnCardSelections);

        Board = FindObjectOfType <GameBoardBehaviour>();

        AnimationEngine = FindObjectOfType <AnimationEngineBehaviour>();
        AnimationEngine.OnComplete.AddListener(onAnimationsComplete);

        lobbyInfo = LobbyInfoController.Instance();
        if (lobbyInfo != null && lobbyInfo.msg != null)
        {
            WebSocketListener.Instance().StartListening(lobbyInfo.msg.id, lobbyInfo.playerName, () => {
                Debug.Log("I'm listening...");
                if (lobbyInfo.gameStartMessage != null)
                {
                    handleDownStreamMessage(MsgTypes.GAME_START, lobbyInfo.gameStartMessage);
                }
            });
        }
    }
Esempio n. 19
0
        public WsServer(ushort port, Func <WebSocket, Task> process)
        {
            var       timeout      = TimeSpan.FromSeconds(3);
            var       rwTimeout    = TimeSpan.FromMilliseconds(200);
            const int bufferSize   = 1024 * 8;
            const int buffersCount = 100;

            var options = new WebSocketListenerOptions
            {
                PingTimeout              = timeout,
                NegotiationTimeout       = timeout,
                PingMode                 = PingMode.BandwidthSaving,
                ParallelNegotiations     = 16,
                NegotiationQueueCapacity = 256,
                BufferManager            = BufferManager.CreateBufferManager(bufferSize * buffersCount, bufferSize),
                Logger = new ILogWrapper(Log),
            };

            options.Standards.RegisterRfc6455(_ => {});

            options.Transports.ConfigureTcp(tcp =>
            {
                tcp.BacklogSize       = 100;           // max pending connections waiting to be accepted
                tcp.ReceiveBufferSize = bufferSize;
                tcp.SendBufferSize    = bufferSize;
                tcp.ReceiveTimeout    = rwTimeout;
                tcp.SendTimeout       = rwTimeout;
            });

            var endpoint = new IPEndPoint(IPAddress.Loopback, port);

            listener     = new WebSocketListener(endpoint, options);
            this.process = process ?? throw new ArgumentException("can't be null", nameof(process));
        }
 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);
 }
        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));
        }
Esempio n. 22
0
        async Task AcceptWebSocketClients(WebSocketListener server, CancellationToken token)
        {
            while (!token.IsCancellationRequested && !this.stopServer)
            {
                try
                {
                    var ws = await server.AcceptWebSocketAsync(token).ConfigureAwait(false);

                    if (ws == null)
                    {
                        continue;
                    }

                    logDelegate("AcceptWebSocketClients " + ws.RemoteEndpoint.ToString());
                    sockets.Add(ws);

                    Task.Run(() => HandleConnectionAsync(ws, token));
                }
                catch (Exception aex)
                {
                    var ex = aex.GetBaseException();
                    logDelegate("Error Accepting client: " + ex.GetType().Name + ": " + ex.Message);
                }
            }
            logDelegate("Server Stop accepting clients");
        }
Esempio n. 23
0
        public void start(String ip, int port)
        {
            //var endP = new IPEndPoint(IPAddress.Parse(ip), port);

            try
            {
                cancellation = new CancellationTokenSource();

                var endpoint = new IPEndPoint(IPAddress.Parse(ip), port);
                // var endpoint = new IPEndPoint(IPAddress.Any, port);
                server = new WebSocketListener(endpoint, new WebSocketListenerOptions()
                {
                    SubProtocols = new[] { "text" }
                });
                server.Standards.RegisterStandard(new WebSocketFactoryRfc6455());
                server.StartAsync();

                logDelegate("Server started at " + endpoint.ToString());

                // start listening for client connection
                var task = Task.Run(() => AcceptWebSocketClients(server, cancellation.Token));
            }
            catch (Exception ex)
            {
                logDelegate("Error Starting socket server: " + ex.Message);
            }
        }
    private void Start()
    {
        WebSocketListener.Instance().Subscribe(this);
        LobbyInfoController lobby = LobbyInfoController.Instance();

        updateLobbyName(lobby.msg.id);
    }
        public CommsServer(string linkName, string prefix, object commandStructure, int port = 80, Func <TCPCommand, TCPCommand, bool> checkMessage = null, bool consoleEcho = false)
        {
            if (!prefix.StartsWith("/"))
            {
                prefix = "/" + prefix;
            }

            webSocketListeners = new List <WebSocketListener>();
            _linkName          = linkName;
            _token             = new CancellationTokenSource();
            _commandStructure  = commandStructure;

            bool needsStarting = false;

            if (wssv == null)
            {
                wssv          = new WebSocketServer(port);
                needsStarting = true;
            }

            wssv.AddWebSocketService <WebSocketListener>(prefix, () =>
            {
                WebSocketListener gl = new WebSocketListener(commandStructure, this, consoleEcho, checkMessage);
                webSocketListeners.Add(gl);
                return(gl);
            });

            if (needsStarting)
            {
                wssv.Start();
            }
        }
        public async Task StartServerAsync([NotNull] Func <ButtplugServer> aFactory, uint aMaxConnections = 1, int aPort = 12345, bool aLocalOnly = true, string aCertPath = null, string aKeyPath = null)
        {
            _cancellation  = new CancellationTokenSource();
            _serverFactory = aFactory;

            _maxConnections = aMaxConnections;

            _logManager = new ButtplugLogManager();
            _logger     = _logManager.GetLogger(GetType());

            var endpoint = new IPEndPoint(aLocalOnly ? IPAddress.Loopback : IPAddress.Any, aPort);

            var options = new WebSocketListenerOptions();

            options.Standards.RegisterRfc6455();

            if (aCertPath != null && aKeyPath != null)
            {
                var cert = CertUtils.LoadPEMCert(aCertPath, aKeyPath);
                options.ConnectionExtensions.RegisterSecureConnection(cert);
            }

            _server = new WebSocketListener(endpoint, options);
            await _server.StartAsync().ConfigureAwait(false);

            _websocketTask = Task.Run(() => AcceptWebSocketClientsAsync(_server, _cancellation.Token));
        }
Esempio n. 27
0
        public SocketServer()
        {
            Server = new WebSocketListener(new IPEndPoint(IPAddress.Any, Port));
            Server.Standards.RegisterStandard(new WebSocketFactoryRfc6455());
            Server.StartAsync();

            Task.Run(() => Listen(Cancellation.Token));
        }
Esempio n. 28
0
        private static void InitiateWebSocks()
        {
            WebSocks.packets.Handler.AddHandlers();
            WebSocketListener.InitiateListener();

            Out.WriteLog("WebSocks - ready to listen!", "SUCCESS");
            Out.WriteLog("WebSocks started.");
        }
        public async void ConnectToServer(WebSocketListener webSocketListener, Uri serverUri)
        {
            _webSocketListener = webSocketListener;
            await ConnectToSocket(serverUri);

            Console.WriteLine("Web socket closed");
            Console.ReadKey();
        }
        public void RunServer()
        {
            var server  = new WebSocketListener(new IPEndPoint(IPAddress.Any, 8006));
            var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(server);

            server.Standards.RegisterStandard(rfc6455);
            server.Start();
        }
 public WebSocketFactoryRfc6455(WebSocketListener listener)
     : base(listener)
 {
 }