public void SetUp()
 {
     _server = new WebSocketServer(54321, IPAddress.Loopback) {OnReceive = OnServerReceive};
     _server.Start();
     _client = new WebSocketClient("ws://127.0.0.1:54321/path") { Origin = "localhost", OnReceive = OnClientReceive };
     _client.Connect();
 }
 public void Dispose()
 {
     _client.Disconnect();
     _server.Stop();
     _client = null;
     _server = null;
 }
Ejemplo n.º 3
0
 public static void Start()
 {
     Server = new WebSocketServer(81, IPAddress.Any);
     Server.OnConnect = OnConnected;
     Server.Start();
     Utilities.Logger.Infos("Websocket server started !");
 }
Ejemplo n.º 4
0
        internal static bool Init(int bindPort, int maxConnections)
        {
            _Port = bindPort;
             _maxConnections = maxConnections;
             _activeConnections = new HashSet<int>();

             try
             {
                 var aServer = new WebSocketServer(_Port, IPAddress.Any)
                 {
                     OnReceive = OnReceive,
                     OnSend = OnSend,
                     OnConnected = OnConnect,
                     OnDisconnect = OnDisconnect,
                     TimeOut = new TimeSpan(0, 5, 0)
                 };
                 aServer.Start();
                 Console.WriteLine("    WebSockets initialized, listining on port: " + _Port + ".");
                 return true;
             }
             catch
             {
                 Console.WriteLine("    failed to initialize WebSockets!");
                 return false;
             }
        }
Ejemplo n.º 5
0
 public void TearDown()
 {
     _client.Disconnect();
     _server.Stop();
     _client = null;
     _server = null;
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Starts the specified port number.
        /// </summary>
        /// <param name="portNumber">The port number.</param>
        public void Start(int portNumber)
        {
            try
            {
                WebSocketServer = new WebSocketServer(portNumber, IPAddress.Any)
                {
                    OnConnected = OnAlchemyWebSocketClientConnected,
                    TimeOut = TimeSpan.FromHours(24)
                };

                WebSocketServer.Start();

                _hasStarted = true;
            }
            catch (SocketException ex)
            {
                _logger.ErrorException("The web socket server is unable to start on port {0} due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system.", ex, portNumber);

                throw;
            }

            Port = portNumber;

            _logger.Info("Alchemy Web Socket Server started");
        }
        public void ClientShouldNotConnectWithInvalidProtocol()
        {
            _server = new WebSocketServer(54321, IPAddress.Loopback);
            _server.Start();
            _client = new WebSocketClient("ws://127.0.0.1:54321/path")
                          {Origin = "localhost", SubProtocols = new[] {"test", "test2"}};

            _client.Connect();
        }
Ejemplo n.º 8
0
        public MasterServer()
        {
            sessions = new List<ClientSession>();

            server = new WebSocketServer(9998,IPAddress.Any);
            server.OnConnected = OnConnected;
            server.OnReceive = OnReceive;
            server.Start();
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Initializes the WebSocket server and begins accepting connections.
 /// </summary>
 public static void Intitialize()
 {
     wsserver = new WebSocketServer(Config.ServerPort, IPAddress.Any);
     wsserver.OnConnect = OnConnect;
     wsserver.OnConnected = OnConnected;
     wsserver.OnDisconnect = OnDisconnect;
     wsserver.OnReceive = OnReceive;
     wsserver.OnSend = OnSend;
     wsserver.Start();
 }
Ejemplo n.º 10
0
        public void ClientShoulConnectWithValidProtocol()
        {
            _server = new WebSocketServer(54321, IPAddress.Loopback) { SubProtocols = new[] { "test" }};
            _server.Start();
            _client = new WebSocketClient("ws://127.0.0.1:54321/path") { Origin = "localhost", SubProtocols = new[] { "test", "test2" } };

            _client.Connect();

            Assert.IsTrue(_client.IsAuthenticated);
            Assert.AreEqual("test", _client.CurrentProtocol);
        }
Ejemplo n.º 11
0
 public Websocket()
 {
     ws = new WebSocketServer(9000, System.Net.IPAddress.Any)
     {
         OnReceive = ReceivedMsg,
         OnConnected = newConnection,
         OnConnect = attemptingConnect,
         OnDisconnect = DisconnectedConnection
     };
     ws.Start();
 }
Ejemplo n.º 12
0
        public void Start()
        {
            InitializeSavedJukeboxes();

            // Small race condition exists now; we may not set the OnReceive handler before data comes in
            socketServer = new WebSocketServer(Constants.WebSocketPort, IPAddress.Any);
            socketServer.OnConnect += OnConnect;
            socketServer.OnDisconnect += OnDisconnect;
            socketServer.Start();

            ts.TraceEvent(TraceEventType.Information, 0, "Started");
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AlchemyWampHost"/> class.
 /// </summary>
 /// <param name="address">IP address for current host</param>
 /// <param name="port">Listening port</param>
 public AlchemyWampHost(IPAddress address, int port)
     : base(new Uri("ws://" + address + ":" + port), new NewtonsoftWampMessageProvider(), new NewtonsoftTypeResolver())
 {
     _endpointSessions = new Dictionary<EndPoint, IWampSession>();
     _server = new WebSocketServer(port, address)
                   {
                       OnReceive = OnReceive,
                       OnConnected = OnConnected,
                       OnDisconnect = OnDisconnect,
                       OnSend = OnSend
                   };
 }
Ejemplo n.º 14
0
        private static void Main(string[] args)
        {
            var aServer = new WebSocketServer(81, IPAddress.Any)
            {
                OnReceive = OnReceive,
                TimeOut = new TimeSpan(0, 5, 0)
            };

            aServer.Start();

            if (!SpotifyAPI.IsSpotifyRunning())
            {
                spotifyClient.RunSpotify();
                Thread.Sleep(5000);
            }

            if (!SpotifyAPI.IsSpotifyWebHelperRunning())
            {
                spotifyClient.RunSpotifyWebHelper();
                Thread.Sleep(4000);
            }

            if (!spotifyClient.Connect())
            {
                Console.WriteLine("SpotifyAPI couldn't load!");
            }

            var mh = spotifyClient.GetMusicHandler();
            var eh = spotifyClient.GetEventHandler();

            spotifyClient.Update();

            Song = mh.GetCurrentTrack().GetTrackName();
            Artist = mh.GetCurrentTrack().GetArtistName();
            Album = mh.GetCurrentTrack().GetAlbumName();
            AlbumURL = mh.GetCurrentTrack().GetAlbumArtURL(AlbumArtSize.SIZE_320);
            Volume = "100%";

            Time = formatTime(0) + "/" + formatTime(mh.GetCurrentTrack().GetLength());

            Length = mh.GetCurrentTrack().GetLength();

            eh.OnTrackChange += TrackChange;
            eh.OnVolumeChange += VolumeChange;
            eh.OnTrackTimeChange += TimeChange;

            eh.ListenForEvents(true);

            while (true)
            {
                Thread.Sleep(1000);
            }
        }
 public AlchemyWebSocketServer(int port, IPAddress ipAddress, TimeSpan timeout, IUserDatabase userDatabase)
     : base(userDatabase)
 {
     server = new WebSocketServer(port, ipAddress)
                  {
                      TimeOut = timeout,
                      FlashAccessPolicyEnabled = true,
                      OnConnected = OnConnected,
                      OnDisconnect = OnDisconnect,
                      OnReceive = OnReceive,
                      OnSend = OnSend
                  };
 }
Ejemplo n.º 16
0
 public WebsocketGraph(TimeSpan timeout, int port, int? historySendOnConnectCount)
 {
     m_aServer = new WebSocketServer(port, System.Net.IPAddress.Any)
     {
         OnReceive = OnReceive,
         OnSend = OnSend,
         OnConnected = OnConnect,
         OnDisconnect = OnDisconnect,
         TimeOut = timeout
     };
     m_historySendOnConnectCount = historySendOnConnectCount;
     m_aServer.Start();
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Starts the specified port number.
        /// </summary>
        /// <param name="portNumber">The port number.</param>
        public void Start(int portNumber)
        {
            WebSocketServer = new WebSocketServer(portNumber, IPAddress.Any)
            {
                OnConnected = OnAlchemyWebSocketClientConnected,
                TimeOut = TimeSpan.FromHours(12)
            };

            WebSocketServer.Start();

            Port = portNumber;

            _logger.Info("Alchemy Web Socket Server started");
        }
Ejemplo n.º 18
0
        static void Main(string[] arguments)
        {
            ActiveContexts = new List<UserContext>();

            WebSocketServer server = new WebSocketServer(81, IPAddress.Any)
            {
                OnReceive = OnReceive,
                OnSend = OnSend,
                OnConnected = OnConnect,
                OnDisconnect = OnDisconnect,
                TimeOut = new TimeSpan(0, 0, 5)
            };

            server.Start();
        }
Ejemplo n.º 19
0
        public void Start(WebSocketHandler handler)
        {
            _server =   new WebSocketServer(81, IPAddress.Any)
                        {
                            OnReceive = new OnEventDelegate(handler.OnReceive),
                            OnSend = new OnEventDelegate(handler.OnSend),
                            OnConnect = new OnEventDelegate(handler.OnConnect),
                            OnConnected = new OnEventDelegate(handler.OnConnected),
                            OnDisconnect = new OnEventDelegate(handler.OnDisconnect),
                            TimeOut = new TimeSpan(0, 5, 0)
                        };

            Console.WriteLine("Starting Server");

            _server.Start();
        }
        public static void run()
        {
            //subscribe to the right event
            InterceptKeys.OnKeyPressedEvent += new onKeyPressed(listenKeyPressed);
            InterceptKeys.OnKeyReleasedEvent += new onKeyReleased(listenKeyReleased);
            MouseHook.OnMousePressedEvent += new onMousePressed(listenMousePressed);
            MouseHook.OnMouseReleasedEvent += new onMouseReleased(listenMouseReleased);
            //We're running the server locally
            aServer = new WebSocketServer(3939, IPAddress.Parse("127.0.0.1"))
            {
                OnConnected = OnConnected,
                OnDisconnect = OnDisconnect,
                TimeOut = new TimeSpan(0, 5, 0)
            };

            aServer.Start();
        }
Ejemplo n.º 21
0
        public TossServer()
        {
            aServer = new WebSocketServer(false, 81, IPAddress.Any)
            {
                OnReceive = OnReceive,
                OnSend = OnSend,
                OnConnect = OnConnect,
                OnDisconnect = OnDisconnect,
                TimeOut = new TimeSpan(0, 5, 0)
            };

            aServer.Start();

            pmsSrv = new PMSServer();
            pmsSrv.ReqPMSSetEvent += pmsSrv_ReqPMSSetEvent;

            cdrSrv = new CDRecorder();
            cdrSrv.RequestCDREvent += cdrSrv_RequestCDREvent;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Starts the specified port number.
        /// </summary>
        /// <param name="portNumber">The port number.</param>
        public void Start(int portNumber)
        {
            _logger.Info("Starting Alchemy web socket server on port {0}", portNumber);

            try
            {
                WebSocketServer = new WebSocketServer(portNumber, IPAddress.Any)
                {
                    OnConnected = OnAlchemyWebSocketClientConnected,
                    TimeOut = TimeSpan.FromHours(24)
                };

                #if __MonoCS__
                //Linux: port below 1024 require root or cap_net_bind_service
                if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
                {
                    if (Syscall.getuid() == 0)
                    {
                        WebSocketServer.FlashAccessPolicyEnabled = true;
                    }
                    else
                    {
                        WebSocketServer.FlashAccessPolicyEnabled = false;
                    }
                }
                #endif
                WebSocketServer.Start();
            }
            catch (Exception ex)
            {
                _logger.ErrorException("The web socket server is unable to start on port {0} due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system.", ex, portNumber);

                throw;
            }

            Port = portNumber;

            _logger.Info("Alchemy Web Socket Server started");
        }
Ejemplo n.º 23
0
        public WebSocket(int port, string chromeExtensionOrigin)
        {
            this.Port = port;
            this.ChromeExtensionOrigin = chromeExtensionOrigin;

            _clients = new List<UserContext>();

            var chromeExt = "";
            if (!string.IsNullOrEmpty(ChromeExtensionOrigin))
                chromeExt = "chrome-extension://" + ChromeExtensionOrigin;

            _server = new WebSocketServer(this.Port, IPAddress.Loopback)
            {
                OnReceive = OnReceive,
                OnConnected = OnConnect,
                OnDisconnect = OnDisconnect,
                TimeOut = new TimeSpan(0, 5, 0),
                Origin = chromeExt
            };

            _server.Start();
        }
 public WebSocketServerWrapper(int port = 81, IPAddress ipAddress = null)
 {
     _webSocketServer = new Alchemy.WebSocketServer(port, (ipAddress ?? IPAddress.Any))
     {
         TimeOut = TimeSpan.FromMilliseconds(-1)
     };
     _webSocketServer.OnConnect = new OnEventDelegate((uctx) =>
     {
         var oc = OnConnect;
         if (null != oc)
             oc(this, new UserContextEventArgs(uctx));
     });
     _webSocketServer.OnConnected = new OnEventDelegate((uctx) =>
     {
         var oc = OnConnected;
         if (null != oc)
             oc(this, new UserContextEventArgs(uctx));
     });
     _webSocketServer.OnDisconnect = new OnEventDelegate((uctx) =>
     {
         var oc = OnDisconnect;
         if (null != oc)
             oc(this, new UserContextEventArgs(uctx));
     });
     _webSocketServer.OnReceive = new OnEventDelegate((uctx) =>
     {
         var or = OnReceive;
         if (null != or)
             or(this, new UserContextEventArgs(uctx));
     });
     _webSocketServer.OnSend = new OnEventDelegate((uctx) =>
     {
         var os = OnSend;
         if (null != os)
             os(this, new UserContextEventArgs(uctx));
     });
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Initialize the application and start the Alchemy Websockets server
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // Initialize the server on port 81, accept any IPs, and bind events.
            var aServer = new WebSocketServer(81, IPAddress.Any)
                              {
                                  OnReceive = OnReceive,
                                  OnSend = OnSend,
                                  OnConnected = OnConnect,
                                  OnDisconnect = OnDisconnect,
                                  TimeOut = new TimeSpan(0, 5, 0)
                              };

            aServer.Start();

            // Accept commands on the console and keep it alive
            var command = string.Empty;
            while (command != "exit")
            {
                command = Console.ReadLine();
            }

            aServer.Stop();
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            string SslFileName = @"C:\Astros\AstrosSocket\astros.com.pfx";
            string SslPassword = @"c0sm0s";
            bool IsSecure = true;

            WebSocketServer wss = new WebSocketServer(11234, IPAddress.Any)
            {
                OnReceive = OnReceive,
                OnConnect = OnConnect,
                OnSend = OnSend,
                OnDisconnect = OnDisconnect,
                OnConnected = OnConnected,
                FlashAccessPolicyEnabled = true,
                IsSecure = IsSecure,
                SSLCertificate = new X509Certificate2(SslFileName, SslPassword)
            };

            Console.Title = "WebSocket Server Test";
            Console.WriteLine("Starting server...");
            wss.Start();
            Console.WriteLine(" ... Server started");

            Console.WriteLine("Waiting for incomming connections...");
            Console.WriteLine("[Press enter to end server]");

            string str = string.Empty;
            //while (string.IsNullOrEmpty(str) == true)
            {
                str = Console.ReadLine();
            }

            Console.WriteLine("Stopping server...");
            wss.Stop();
            Console.WriteLine(" ... Server stopped");

            // Force the program to terminate
            Environment.Exit(0);
        }
Ejemplo n.º 27
0
        public void Initialize(int port, string password, int adminId, long ssid)
        {
            this.Stop();

            // Clear the message handling queue
            _messageQueue.Clear();
            this.OnMessageQueueUpdated();

            // Find existing state
            var existing = LoadState(ssid);
            
            _state = existing ?? new SyncState(ssid);

            _password = password;
            _adminId = adminId;
            _subSessionId = ssid;

            // Start new server
            _server = new WebSocketServer(port, IPAddress.Any)
            {
                OnReceive = OnReceive,
                OnConnected = OnConnected,
                OnDisconnect = OnDisconnect,
                TimeOut = new TimeSpan(0, 5, 0)
            };

            _server.Start();
            this.Status = ServerStatus.Active;

            _localServerInfo = ServerInfo.Local(port, password);

            // Start message queue handling thread
            _messageThread = new Thread(HandleMessageQueue);
            _messageThread.IsBackground = false;
            _messageThread.Start();

            // Start ping loop
            _pingThread = new Thread(PingLoop);
            _pingThread.IsBackground = true;
            _pingThread.Start();

            // Start web-update thread
            _webThread = new Thread(WebUpdateLoop);
            _webThread.IsBackground = true;
            _webThread.Start();
        }
Ejemplo n.º 28
0
        public void Stop()
        {
            // Stop server
            if (_server != null)
            {
                // Save state
                this.SaveState();

                // TODO: Disconnect everyone
                this.BroadcastDisconnect();
                foreach (var conn in _connections)
                {
                    if (conn.IsRegistered)
                    {
                        conn.User.IsConnected = false;
                        conn.User.IsRegistered = false;
                    }
                }
                foreach (var conn in _connections)
                {
                    conn.User = null;
                }
                _connections.Clear();

                _server.Stop();
                _server.Dispose();
            }
            _server = null;
            this.Status = ServerStatus.Stopped;

            _localServerInfo = null;

            _messageQueue.Clear();
            this.OnMessageQueueUpdated();

            // Stop threads
            if (_messageThread != null)
            {
                _messageThread.Abort();
                _messageThread = null;
            }

            if (_pingThread != null)
            {
                _pingThread.Abort();
                _pingThread = null;
            }

            if (_webThread != null)
            {
                _webThread.Abort();
                _webThread = null;
            }
        }
Ejemplo n.º 29
0
        private void SetupWebSocketServer()
        {
            try
            {
                this.server = new WebSocketServer(8181, IPAddress.Any)
                {
                    OnReceive = OnReceive,
                    //OnSend = OnSend,
                    //OnConnect = OnConnect,
                    OnConnected = OnConnected,
                    OnDisconnect = OnDisconnect,
                    TimeOut = new TimeSpan(0, 5, 0)
                };

                this.server.Start();
                this.LogWindow("WebSocket Server started: 'ws://localhost:8181'.", true);

            }
            catch (Exception excep)
            {
                Console.WriteLine(excep);
            }
        }
Ejemplo n.º 30
0
        // Constructor
        public MainForm( )
        {
            InitializeComponent( );
            Application.Idle += new EventHandler( Application_Idle );

            aServer = new WebSocketServer(8100, System.Net.IPAddress.Any)
            {
                OnReceive = OnReceive,
                OnSend = OnSend,
                OnConnected = OnConnect,
                OnDisconnect = OnDisconnect,
                TimeOut = new TimeSpan(0, 5, 0)
            };
            aServer.Start();
        }