Ejemplo n.º 1
5
        public static void Main(string [] args)
        {
            var wssv = new WebSocketServer (4649);
              //var wssv = new WebSocketServer (4649, true);
              //var wssv = new WebSocketServer ("ws://localhost:4649");
              //var wssv = new WebSocketServer ("wss://localhost:4649");
              #if DEBUG
              wssv.Log.Level = LogLevel.TRACE;
              #endif
              //var cert = ConfigurationManager.AppSettings ["ServerCertFile"];
              //var password = ConfigurationManager.AppSettings ["CertFilePassword"];
              //wssv.Certificate = new X509Certificate2 (cert, password);
              //wssv.KeepClean = false;
              wssv.AddWebSocketService<Echo> ("/Echo");
              wssv.AddWebSocketService<Chat> ("/Chat");
              //wssv.AddWebSocketService<Chat> ("/Chat", () => new Chat ("Anon#"));
              //wssv.AddWebSocketService<Echo> ("/エコー");
              //wssv.AddWebSocketService<Chat> ("/チャット");

              wssv.Start ();
              if (wssv.IsListening)
              {
            Console.WriteLine (
              "A WebSocket Server listening on port: {0} service paths:", wssv.Port);

            foreach (var path in wssv.WebSocketServices.ServicePaths)
              Console.WriteLine ("  {0}", path);
              }

              Console.WriteLine ("\nPress Enter key to stop server...");
              Console.ReadLine ();

              wssv.Stop ();
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            var config = new ServerConfig {
                Name = "SuperWebSocket",
                Ip = "Any",
                Port = 2012,
                Mode = SocketMode.Tcp,
            };

            Console.WriteLine("Starting WebSocketServer on port " + config.Port + "...");

            var socketServer = new WebSocketServer();
            socketServer.Setup(new RootConfig(), config);

            socketServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(socketServer_NewMessageReceived);
            socketServer.NewSessionConnected += new SessionHandler<WebSocketSession>(socketServer_NewSessionConnected);
            socketServer.SessionClosed += new SessionHandler<WebSocketSession, CloseReason>(socketServer_SessionClosed);

            if (!socketServer.Start()) {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("The server started successfully, press 'q' key to stop it!");

            while (Console.ReadKey().KeyChar != 'q') {
                Console.WriteLine();
                continue;
            }
            socketServer.Stop();

            Console.WriteLine("\nThe server stopped!");
        }
Ejemplo n.º 3
0
        public WebSocketInterface(int port)
        {
            _server = new WebSocketServer();
            var setupComplete = _server.Setup(new ServerConfig
            {
                Name = "NecroWebSocket",
                Ip = "Any",
                Port = port,
                Mode = SocketMode.Tcp,
                Security = "tls",
                Certificate = new CertificateConfig
                {
                    FilePath = @"cert.pfx",
                    Password = "******"
                }
            });

            if (setupComplete == false)
            {
                Logger.Write($"Failed to start WebSocketServer on port : {port}", LogLevel.Error);
                return;
            }

            _server.NewMessageReceived += HandleMessage;
            _server.NewSessionConnected += HandleSession;

            _server.Start();
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Context"/> class.
 /// </summary>
 public Context(WebSocketServer server, TcpClient connection)
 {
     Server = server;
     Connection = connection;
     Buffer = new byte[_bufferSize];
     UserContext = new UserContext(this) {ClientAddress = connection.Client.RemoteEndPoint};
 }
Ejemplo n.º 5
0
 public void Start(string address, int port, string path)
 {
     IPAddress ipaddr = new IPAddress(address.Split('.').Select(a => (byte)a.to_i()).ToArray());
     WebSocketServer wss = new WebSocketServer(ipaddr, port, this);
     wss.AddWebSocketService<ServerReceiver>(path);
     wss.Start();
 }
Ejemplo n.º 6
0
        public void Awake()
        {
            // Just in case cancel all old invokes related to this instance
            CancelInvoke ();

            // Do a full sync
            //FullSync ();

            // Add all vessels to the vessel list
            foreach (Vessel vessel in FlightGlobals.Vessels) {
                if (!all_vessels.Contains (vessel)) {
                    all_vessels.Add (vessel);
                }
            }
            InvokeRepeating ("UpdateClients",1.0F,1.0F);

            if (wssv == null) {
                Debug.Log ("Establishing websocket");
                wssv = new WebSocketServer (12321); //TODO: Add possibility to configure IP
                wssv.AddWebSocketService<MissionControlService> ("/mcs", () => new MissionControlService (this));
                wssv.Start ();

                Debug.Log ("Established websocket!");
            }
        }
Ejemplo n.º 7
0
        public void Start()
        {
            try
            {
                var socketServer = new WebSocketServer(this._port, this._isSSL);
                socketServer.AddWebSocketService<WSClientBehaviour>(this._path);
                if (this._isSSL)
                {
                    //configure SSL for websocket server (just to test this feature!)
                    string basedir = AppDomain.CurrentDomain.BaseDirectory;
                    string certPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(basedir, @"..\serverCertificate.pfx"));
                    if (!System.IO.File.Exists(certPath))
                        throw new Exception("I did not found the SSL certificate for the websocket server");
                    var passwd = "password";
                    socketServer.SslConfiguration.ServerCertificate = new X509Certificate2(certPath, passwd);
                }
               
                socketServer.Log.Output = (logData, msg) =>
                {
                    if (logData.Level == LogLevel.Error || logData.Level == LogLevel.Fatal)
                       this.OnError(new Exception(logData.Message));
                };
               
                this._socketServer = socketServer;
                socketServer.Start();

                MessageService.Start(this);
            }
            catch (Exception ex)
            {
                this.OnError(ex);
            }
        }
Ejemplo n.º 8
0
	private static void Initialize () {
		wsServer = new WebSocketServer(
			WebConsoleDefinitions.SERVE_PROTOCOL + WebConsoleDefinitions.SERVE_ADDRESS + ":" + WebConsoleDefinitions.SERVE_PORT
		);
		wsServer.AddWebSocketService<WSServerInstance>("/");
		wsServer.Start();
	}
        public void Run()
        {
            //websocket init
            Console.WriteLine("tetris server is starting... port:{0}", Port_WebSocket);
            var listener = new WebSocketServer();
            listener.NewMessageReceived += listener_NewMessageReceived;
            listener.NewSessionConnected += listener_NewSessionConnected;

            if (!listener.Setup(Port_WebSocket))
            {
                Console.WriteLine("failed to initialize.");
                return;
            }

            if (!listener.Start())
            {
                Console.WriteLine("failed to start.");
                return;
            }

            //transceiver init
            Console.WriteLine("transceiver is starting... port:{0}", Port_Transceiver);
            var tr = new Transceiver(null, 2013);

            isRunning = true;
            Thread th = new Thread(() =>
            {
                Packet p = new Packet();
                while (isRunning)
                {
                    p.Clear();
                    tr.Receive(ref p);

                    Console.WriteLine("received a packet: {0}", p.Peek());

                    if (conn != null)
                    {
                        try
                        {
                            conn.Send((string)p.Pop());
                        }
            #pragma warning disable 0168
                        catch (Exception ex)
                        {
                            //conn = null;
                        }
            #pragma warning restore 0168
                    }
                }
                tr.Dispose();
            });
            th.Start();

            Console.WriteLine("press enter to terminate server.");
            Console.ReadLine();

            isRunning = false;
            listener.Stop();
            Console.WriteLine("terminating server...");
        }
Ejemplo n.º 10
0
        static void Test1()
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://localhost:8181");
            server.Start(socket =>
                {
                    socket.OnOpen = () =>
                        {
                            Console.WriteLine("Open!");
                            allSockets.Add(socket);
                        };
                    socket.OnClose = () =>
                        {
                            Console.WriteLine("Close!");
                            allSockets.Remove(socket);
                        };
                    socket.OnMessage = message =>
                        {
                            Console.WriteLine(message);
                            allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                        };
                });

            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }
		public void BasicRoundTrip()
		{
			var serializer = new JsonCommonSerializer();

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

			var listener = new WebSocketServer("ws://localhost:" + port);
			var serverTransport = listener.GenerateTransportSource("/p1");
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<IMyService>(new MyService());
			listener.Start();

			var client = new WebSocket("ws://localhost:" + port + "/p1");
			var clientTransport = client.GenerateTransportSource();
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<IMyService>();
			client.Connect();

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

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

			serverRouter.Dispose();
			serverTransport.Dispose();
			listener.Stop();
		}
Ejemplo n.º 12
0
 public MainWindow()
 {
     InitializeComponent();
     wsServer = new WebSocketServer(IPAddress.Parse("127.0.0.1"), 1234);
     wsServer.AddWebSocketService<Echo>("/");
     wsServer.Start();
 }
Ejemplo n.º 13
0
        static void Main()
        {
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://localhost:8181");
            server.Start(socket =>
                {
                    socket.OnOpen = () =>
                        {
                            Console.WriteLine("Open!");
                            allSockets.Add(socket);
                        };
                    socket.OnClose = () =>
                        {
                            Console.WriteLine("Close!");
                            allSockets.Remove(socket);
                        };
                    socket.OnMessage = message =>
                        {
                            Console.WriteLine(message);
                        };
                });

            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            //int port = int.Parse(args[0]);
            int port = 443;
            ServerConfig serverConfig = new ServerConfig
            {
                Name = "SecureSuperWebSocket",
                Ip = "Any",
                Port = port,
                MaxRequestLength = 10485760,
                SendingQueueSize = 500,
                ReceiveBufferSize = 2050 * 1024,
                //SendBufferSize = 600 * 1024,
            };

            socketServer = new WebSocketServer();
            socketServer.NewSessionConnected += SocketServer_NewSessionConnected;
            socketServer.NewDataReceived += SocketServer_NewDataReceived;
            //socketServer.NewMessageReceived += SocketServer_NewMessageReceived;
            socketServer.Setup(serverConfig);
            socketServer.Start();

            Console.WriteLine("Server is running on port {0} ...", port);

            Console.ReadKey();
        }
Ejemplo n.º 15
0
 public void SetUp()
 {
     server = new WebSocketServer(URI.Port);
     server.AddService<Echo>(URI.AbsolutePath);
     server.Start();
     handle = new EventWaitHandle(false, EventResetMode.AutoReset);
 }
Ejemplo n.º 16
0
        public static void Main()
        {
            var server = new WebSocketServer("127.0.0.1", 8080);
            server.Started += (sender, args) => Console.WriteLine("Server started!");
            server.Stopped += (sender, args) => Console.WriteLine("Server stopped!");

            Console.WriteLine("Tully WebSocket server at your command");
            var exit = false;
            server.Start();

            while (!exit)
            {
                var cmd = Console.ReadLine();

                switch (cmd)
                {
                    case "/exit":
                        exit = true;
                        break;
                    case "/start":
                        server.Start();
                        break;
                    case "/stop":
                        server.Stop();
                        break;
                    default:
                        Console.WriteLine("Unknown command " + cmd);
                        break;
                }
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
Ejemplo n.º 17
0
        public WebSocketInterface(int port, Session session)
        {
            _session = session;
            var translations = session.Translation;
            _server = new WebSocketServer();
            _websocketHandler = WebSocketEventManager.CreateInstance();
            var setupComplete = _server.Setup(new ServerConfig
            {
                Name = "NecroWebSocket",
                Ip = "Any",
                Port = port,
                Mode = SocketMode.Tcp,
                Security = "tls",
                Certificate = new CertificateConfig
                {
                    FilePath = @"cert.pfx",
                    Password = "******"
                }
            });

            if (setupComplete == false)
            {
                Logger.Write(translations.GetTranslation(TranslationString.WebSocketFailStart, port), LogLevel.Error);
                return;
            }

            _server.NewMessageReceived += HandleMessage;
            _server.NewSessionConnected += HandleSession;

            _server.Start();
        }
Ejemplo n.º 18
0
        public void Setup()
        {
            _symbols = new List<Symbol>()
            {
                Symbol.Create("AAPL", SecurityType.Equity, Market.USA),
                Symbol.Create("AIG", SecurityType.Equity, Market.USA)
            };

            Config.Set("live-data-url", "ws://127.0.0.1");
            Config.Set("live-data-port", "8080");

            _mockServerBehavior = new MockServerBehavior();
            _dataQueueHandler = new ApiDataQueueHandler();
            var liveDataUri = new Uri(Config.Get("live-data-url"));
            var uriBuilder = new UriBuilder(liveDataUri);
            uriBuilder.Port = Config.GetInt("live-data-port");

            Task.Run(() =>
            {
                _mockServer = new WebSocketServer(uriBuilder.ToString());
                _mockServer.AddWebSocketService("/", () => _mockServerBehavior);

                Log.Trace("ApiDataQueueHandlerTests.Setup(): Starting the mock server.");
                _mockServer.Start();

                while (true)
                {
                    Thread.Sleep(1000);
                }
            });
        }
        private WebSocketServer ws = null; //SuperWebSocket中的WebSocketServer对象

        #endregion Fields

        #region Constructors

        public BoardcastWebSocket()
        {
            ws = new WebSocketServer();//实例化WebSocketServer

            //添加事件侦听
            ws.NewSessionConnected += ws_NewSessionConnected;//有新会话握手并连接成功
            ws.SessionClosed += ws_SessionClosed;//有会话被关闭 可能是服务端关闭 也可能是客户端关闭
        }
Ejemplo n.º 20
0
 public static void Init(string ID)
 {
     if (s_wssvr == null) {
         s_wssvr = new WebSocketServer("ws://localhost:44444");
     }
     s_wssvr.AddWebSocketService<DeviceManager> (ID);
     Console.WriteLine ("DeviceManagerID={0}", ID);
 }
Ejemplo n.º 21
0
 public WebChat()
 {
     ws = new WebSocketServer();
     ws.NewSessionConnected += ws_NewSessionConnected;
     ws.NewMessageReceived += ws_NewMessageReceived;
     ws.NewDataReceived += ws_NewDataReceived;
     ws.SessionClosed += ws_SessionClosed;
 }
Ejemplo n.º 22
0
        public void Setup()
        {
            _repository = new MockRepository(MockBehavior.Default);
<<<<<<< HEAD
            _server = new WebSocketServer(IPAddress.Any, 8000);
=======
            _server = new WebSocketServer("ws://0.0.0.0:8000");
>>>>>>> statianzo/master
        }
Ejemplo n.º 23
0
 public static void Main(string[] args)
 {
     var wssv = new WebSocketServer("ws://127.0.0.1");
     wssv.AddWebSocketService<CatServer>("/cat");
     wssv.Start();
     Console.WriteLine("Server started");
     Console.ReadKey(true);
     wssv.Stop();
 }
Ejemplo n.º 24
0
 static void Main(string[] args)
 {
     var wssv = new WebSocketServer("ws://localhost:8181/");
     wssv.AddWebSocketService<Laputa>("/");
     Console.WriteLine("Listening...");
     wssv.Start();
     Console.ReadKey(true);
     wssv.Stop();
 }
Ejemplo n.º 25
0
        private WebSocketServer ws = null; //SuperWebSocket中的WebSocketServer对象

        #endregion Fields

        #region Constructors

        public ChatWebSocket()
        {
            ws = new WebSocketServer();//实例化WebSocketServer

            //添加事件侦听
            ws.NewSessionConnected += ws_NewSessionConnected;//有新会话握手并连接成功
            ws.SessionClosed += ws_SessionClosed;//有会话被关闭 可能是服务端关闭 也可能是客户端关闭
            ws.NewMessageReceived += ws_NewMessageReceived;//有客户端发送新的消息
        }
Ejemplo n.º 26
0
        //static Action<IWebSocketConnection> mAction;
        static void Test2()
        {
            FleckLog.Level = LogLevel.Debug;

            mClients = new List<IWebSocketConnection>();

            string SSLFileName;
            string SSLPassword;

            SSLFileName = @"C:\Astros\AstrosSocket\astros.com.pfx";
            SSLPassword = "******";

            string WSLocation;

            //WSLocation = "ws://localhost:8181";
            //WSLocation = "wss://dev.astros.com:8181";
            //WSLocation = "ws://dev.astros.com:11234";
            WSLocation = "wss://dev.astros.com:11234";

            mServer = new WebSocketServer(WSLocation);
            mServer.Certificate = new X509Certificate2(SSLFileName, SSLPassword);

            mServer.Start(socket =>
            {
                socket.OnError = ex =>
                {
                    Console.WriteLine("Error: " + ex.Message);
                };
                socket.OnOpen = () =>
                {
                    IWebSocketConnectionInfo conn = socket.ConnectionInfo;
                    Console.WriteLine("Open! (" + conn.ClientIpAddress + ":" + conn.ClientPort.ToString() + ")");
                    mClients.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    mClients.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    mClients.ToList().ForEach(s => s.Send("Echo: " + message));
                };
            });

            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (IWebSocketConnection socket in mClients.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }
Ejemplo n.º 27
0
    static void Main()
    {
        FleckLog.Level = LogLevel.Error;

        var renderers = new ConcurrentDictionary<IWebSocketConnection, IRenderer>();

        var proxyRenderer = new ProxyRenderer();
            proxyRenderer.AddRenderer( new ConsoleRenderer());
        var allSockets = new List<IWebSocketConnection>();
        var server = new WebSocketServer("ws://localhost:8080/websession");
        server.Start(socket =>
        {
            socket.OnOpen = () =>
            {
                allSockets.Add(socket);
                renderers[socket] = new WebRenderer(socket);
                proxyRenderer.AddRenderer(renderers[socket]);

                if (allSockets.Count == 1)
                {
                    var size = new Size(10, 15);
                    var dto = new InitMessageDto(new SizeDto(size));
                    socket.Send(dto.ToJson());

                    var engine = new GameEngine(size, new ConsoleInputListener(), proxyRenderer);
                    engine.Start();
                }
                else
                {
                    var size = new Size(10, 15);
                    var dto = new InitMessageDto(new SizeDto(size));
                    socket.Send(dto.ToJson());
                }
            };
            socket.OnClose = () =>
            {
                allSockets.Remove(socket);
                proxyRenderer.RemoveRenderer(renderers[socket]);

                IRenderer toRemove;
                renderers.TryRemove(socket, out toRemove);
            };
            socket.OnMessage = message =>
            {
                //Console.WriteLine(message);
                //allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
            };
        });

        while (true)
        {
            Thread.Sleep(1000);
        }

           // Console.ReadLine();
    }
Ejemplo n.º 28
0
	public static void Main()
	{
		var server = new WebSocketServer(20080);
		server.OnClientConnected += OnClientConnected;
		Console.WriteLine("Started.");
		var debug_out = new TextWriterTraceListener(Console.Out);
		Trace.Listeners.Add(debug_out);
		Debug.WriteLine("DEBUG");
		server.Run();
	}
Ejemplo n.º 29
0
        public void Stop()
        {
            if (_socketServer != null && _socketServer.IsListening)
            {
                MessageService.Stop();

                _socketServer.Stop();
                _socketServer = null;
            }
        }
Ejemplo n.º 30
0
 private void Button2_Click(object sender, EventArgs e)
 {
     try
     {
         //WebSocekt 监听
         server = new WebSocketServer("ws://" + textBox2.Text + ":" + textBox3.Text);
         server.Start(socket =>
         {
             socket.OnOpen = () =>
             {
                 if (!allClients.ContainsKey(socket))
                 {
                     allClients.Add(socket, false);
                 }
                 isNeedRefreshList = true;
             };
             socket.OnClose = () =>
             {
                 foreach (KeyValuePair <string, List <IWebSocketConnection> > item in clientList)
                 {
                     if (item.Value.Contains(socket))
                     {
                         item.Value.Remove(socket);
                     }
                 }
                 if (allClients.ContainsKey(socket))
                 {
                     allClients.Remove(socket);
                 }
                 isNeedRefreshList = true;
             };
             socket.OnMessage = message =>
             {
                 foreach (KeyValuePair <string, List <IWebSocketConnection> > item in clientList)
                 {
                     try
                     {
                         if (item.Value.Count > 0)
                         {
                             if (item.Value.Contains(socket))
                             {
                                 item.Value.Remove(socket);
                             }
                         }
                     }
                     catch
                     { }
                 }
                 if (!string.IsNullOrEmpty(message))
                 {
                     string[] types = message.Split(',');
                     foreach (string type in types)
                     {
                         if (!clientList.ContainsKey(type))
                         {
                             clientList.Add(type, new List <IWebSocketConnection>());
                         }
                         clientList[type].Add(socket);
                     }
                     if (allClients.ContainsKey(socket))
                     {
                         allClients[socket] = true;
                     }
                 }
                 else
                 {
                     allClients[socket] = false;
                 }
                 isNeedRefreshList = true;
             };
         });
         button1.Enabled = true;
         button2.Enabled = false;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Ejemplo n.º 31
0
        public override void Start(string url, string sslCertificateSerialNumber)
        {
            var uri       = new Uri(url);
            var listenUrl = string.Format("{0}://0.0.0.0:{1}", uri.Scheme, uri.Port);

            _webSocketServer = new WebSocketServer(listenUrl);

            if (sslCertificateSerialNumber != null)
            {
                var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var certificate = store.Certificates
                                  .Find(X509FindType.FindBySerialNumber, sslCertificateSerialNumber, false)
                                  .OfType <X509Certificate2>()
                                  .FirstOrDefault();

                _webSocketServer.Certificate = certificate;
            }

            _logger.Info("Starting WebSocket server");
            _webSocketServer.Start(c =>
            {
                c.OnOpen = () =>
                {
                    _logger.Debug("Opened connection: " + c.ConnectionInfo.Id);
                    RegisterConnection(new FleckWebSocketConnection(c));
                };
                c.OnClose = () =>
                {
                    _logger.Debug("Closed connection: " + c.ConnectionInfo.Id);
                    UnregisterConnection(c.ConnectionInfo.Id);
                };

                c.OnMessage = msg =>
                {
                    _logger.Debug("Received message for connection: " + c.ConnectionInfo.Id);

                    var fc = WaitConnection(c.ConnectionInfo.Id);
                    if (fc == null)
                    {
                        _logger.ErrorFormat("Connection {0} is not registered", c.ConnectionInfo.Id);
                        return;
                    }

                    var e = new WebSocketMessageEventArgs(fc, msg);
                    OnMessageReceived(e);
                };

                c.OnPing = data =>
                {
                    _logger.Debug("Received ping for connection: " + c.ConnectionInfo.Id);

                    var fc = WaitConnection(c.ConnectionInfo.Id);
                    if (fc == null)
                    {
                        _logger.ErrorFormat("Connection {0} is not registered", c.ConnectionInfo.Id);
                        return;
                    }

                    var e = new WebSocketConnectionEventArgs(fc);
                    OnPingReceived(e);

                    c.SendPong(data);
                };
            });
        }
Ejemplo n.º 32
0
 public void Setup()
 {
     _repository = new MockRepository(MockBehavior.Default);
     _server     = new WebSocketServer("ws://0.0.0.0:8000");
 }
Ejemplo n.º 33
0
        public void ShouldNotBeSecureWithWssAndNoCertificate()
        {
            var server = new WebSocketServer("wss://0.0.0.0:8000");

            Assert.IsFalse(server.IsSecure);
        }
Ejemplo n.º 34
0
 public Server(Protocol protocol, string address, int port, string endpoint)
 {
     this.server = new WebSocketServer(GetProtocolAsString(protocol) + "://" + address + ":" + port + "/" + endpoint);
 }
Ejemplo n.º 35
0
        public WebSocketServerManager(string SocketURL)
        {
            FleckLog.Level     = LogLevel.Error;
            FleckLog.LogAction = LogWebsocketException;
            allSockets         = new List <IWebSocketConnection>();
            socketbyName       = new Dictionary <string, IWebSocketConnection>();
            namebySocket       = new Dictionary <IWebSocketConnection, string>();
            server             = new WebSocketServer(SocketURL);
            if (SocketURL.StartsWith("wss://"))
            {
                server.Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("client.habbo.tl.cert.cer");
            }
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    if (allSockets.Contains(socket))
                    {
                        allSockets.Remove(socket);
                    }
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    string name = "";
                    if (namebySocket.ContainsKey(socket))
                    {
                        name = namebySocket[socket].ToString();
                        namebySocket.Remove(socket);
                    }
                    if (socketbyName.ContainsKey(name) && name != "")
                    {
                        socketbyName.Remove(name);
                    }
                    if (allSockets.Contains(socket))
                    {
                        allSockets.Remove(socket);
                    }
                    if (name != "")
                    {
                        using (DatabaseClient dbClient = Essential.GetDatabase().GetClient())
                        {
                            dbClient.AddParamWithValue("name", name);
                            dbClient.ExecuteQuery("UPDATE users SET websocket='0' WHERE username=@name");
                        }
                    }
                };
                socket.OnMessage = message =>
                {
                    var msg = message;
                    int pId = 0;
                    if (!int.TryParse(msg.Split('|')[0], out pId))
                    {
                        return;
                    }
                    if (msg.Length > 1024)
                    {
                        return;
                    }
                    if (msg.StartsWith("1|"))
                    {
                        using (DatabaseClient dbClient = Essential.GetDatabase().GetClient())
                        {
                            dbClient.AddParamWithValue("auth", msg.Substring(2));
                            DataRow drow = null;
                            drow         = dbClient.ReadDataRow("SELECT username FROM users WHERE auth_ticket= @auth LIMIT 1");
                            if (drow == null)
                            {
                                socket.Close();
                            }
                            else
                            {
                                if (socketbyName.ContainsKey((string)drow["username"]))
                                {
                                    socketbyName.Remove((string)drow["username"]);
                                }
                                socketbyName.Add(drow["username"].ToString(), socket);
                                if (namebySocket.ContainsKey(socket))
                                {
                                    namebySocket.Remove(socket);
                                }
                                namebySocket.Add(socket, drow["username"].ToString());
                                dbClient.AddParamWithValue("name", drow["username"].ToString());
                                dbClient.ExecuteQuery("UPDATE users SET websocket='1' WHERE username=@name");
                            }
                        }
                    }
                    else
                    {
                        GameClient Session = Essential.GetGame().GetClientManager().GetClientByHabbo(GetNameByWebSocket(socket));
                        Room room          = null;
                        string[] args      = msg.Split('|');
                        switch (int.Parse(args[0]))
                        {
                        case 6:
                            {
                                try
                                {
                                    room = Essential.GetGame().GetRoomManager().GetRoom(uint.Parse(args[1]));
                                    if (Session != null && room != null)
                                    {
                                        ServerMessage Message = new ServerMessage(Outgoing.RoomForward);
                                        Message.AppendBoolean(false);
                                        Message.AppendUInt(room.Id);
                                        Session.SendMessage(Message);
                                    }
                                }
                                catch { }
                                break;
                            }

                        case 7:
                            {
                                try
                                {
                                    if (Session.GetHabbo().CurrentRoom.CheckRights(Session, false))
                                    {
                                        int ItemId  = int.Parse(args[1]);
                                        double newZ = double.Parse(args[2]);
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28((uint)ItemId);
                                        if (ri != null && ri.GetBaseItem().InteractionType == "stackfield")
                                        {
                                            ri.setHeight(newZ);
                                            ServerMessage smg = new ServerMessage(Outgoing.ObjectUpdate);
                                            ri.Serialize(smg);
                                            Session.GetHabbo().CurrentRoom.SendMessage(smg, null);
                                        }
                                    }
                                }
                                catch { }
                                break;
                            }

                        case 10:
                            {
                                try
                                {
                                    if (Session.GetHabbo().CurrentRoom.CheckRights(Session, false))
                                    {
                                        uint itemid    = uint.Parse(args[1]);
                                        int handitemId = int.Parse(args[2]);
                                        RoomItem ri    = Session.GetHabbo().CurrentRoom.method_28(itemid);
                                        if (ri != null && ri.GetBaseItem().InteractionType == "wf_cnd_has_handitem")
                                        {
                                            ri.string_2 = handitemId.ToString();
                                            ri.UpdateState(true, false);
                                        }
                                    }
                                } catch { }
                                break;
                            }

                        case 12:
                            {
                                try
                                {
                                    if (Session.GetHabbo().CurrentRoom.CheckRights(Session, false))
                                    {
                                        uint itemid = uint.Parse(args[1]);
                                        string team = args[2];
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28(itemid);
                                        if (ri != null && (ri.GetBaseItem().InteractionType == "wf_cnd_actor_in_team" || ri.GetBaseItem().InteractionType == "wf_cnd_not_in_team") && Session.GetHabbo().CurrentRoom.IsValidTeam(team))
                                        {
                                            ri.string_2 = team;
                                            ri.UpdateState(true, false);
                                        }
                                    }
                                } catch { }
                                break;
                            }

                        case 14:
                            {
                                try
                                {
                                    Session.GetHabbo().CurrentRoom.method_56(Session.GetHabbo().Username).CarryItem(int.Parse(args[1]));
                                }
                                catch { }
                                break;
                            }

                        case 18:
                            {
                                if (Session.GetHabbo().CurrentRoom.CheckRights(Session, true))
                                {
                                    try
                                    {
                                        RoomItem ri      = Session.GetHabbo().CurrentRoom.method_28(uint.Parse(args[1]));
                                        string BrandData = "state" + Convert.ToChar(9) + "0";
                                        if (ri == null || ri.GetBaseItem().InteractionType != "background")
                                        {
                                            break;
                                        }
                                        BrandData = BrandData + Convert.ToChar(9) + "imageUrl" + Convert.ToChar(9) + args[2];
                                        BrandData = BrandData + Convert.ToChar(9) + "offsetX" + Convert.ToChar(9) + int.Parse(args[3]);
                                        BrandData = BrandData + Convert.ToChar(9) + "offsetY" + Convert.ToChar(9) + int.Parse(args[4]);
                                        BrandData = BrandData + Convert.ToChar(9) + "offsetZ" + Convert.ToChar(9) + int.Parse(args[5]);
                                        using (DatabaseClient class2 = Essential.GetDatabase().GetClient())
                                        {
                                            class2.AddParamWithValue("extradata", BrandData);
                                            class2.ExecuteQuery("UPDATE items_extra_data SET extra_data = @extradata WHERE item_id = '" + uint.Parse(args[1]) + "' LIMIT 1");
                                        }
                                        ri.ExtraData = BrandData;
                                        Session.GetHabbo().CurrentRoom.method_79(Session, ri, ri.GetX, ri.Int32_1, ri.int_3, false, false, true);
                                        ri.UpdateState(true, false, true);
                                    }
                                    catch (Exception ex) { Core.Logging.LogException(ex.ToString()); }
                                }
                                break;
                            }

                        case 19:
                            {
                                if (Session.GetHabbo().CurrentRoom.CheckRights(Session, true))
                                {
                                    try
                                    {
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28(uint.Parse(args[1]));
                                        if (ri != null && ri.GetBaseItem().InteractionType == "badge_display")
                                        {
                                            string Badge = Session.GetHabbo().GetBadgeComponent().HasBadge(args[2]) ? args[2] : "null";
                                            ri.ExtraData = Badge;
                                            using (DatabaseClient class2 = Essential.GetDatabase().GetClient())
                                            {
                                                class2.AddParamWithValue("extradata", Badge);
                                                class2.ExecuteQuery("UPDATE items_extra_data SET extra_data = @extradata WHERE item_id = '" + uint.Parse(args[1]) + "' LIMIT 1");
                                            }
                                            Session.GetHabbo().CurrentRoom.method_79(Session, ri, ri.GetX, ri.Int32_1, ri.int_3, false, false, true);
                                            ri.UpdateState(true, false, true);
                                        }
                                    }
                                    catch { }
                                }
                                break;
                            }

                        case 21:
                            {
                                if (Session.GetHabbo().CurrentRoom.CheckRights(Session, true))
                                {
                                    try
                                    {
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28(uint.Parse(args[1]));
                                        if (ri != null && ri.GetBaseItem().InteractionType == "wf_act_bot_follow_avatar")
                                        {
                                            string username   = args[2];
                                            int timeinseconds = 30;
                                            if (int.TryParse(args[3], out timeinseconds))
                                            {
                                                RoomUser bot = null;
                                                foreach (RoomUser ru in Session.GetHabbo().CurrentRoom.RoomUsers)
                                                {
                                                    if (ru != null && ru.IsBot && !ru.IsPet && ru.RoomBot.Name == username)
                                                    {
                                                        bot = ru;
                                                    }
                                                }
                                                if (bot != null)
                                                {
                                                    ri.string_2 = username + ";" + timeinseconds;
                                                }
                                                ri.UpdateState(true, false);
                                            }
                                        }
                                    }
                                    catch { }
                                }
                                break;
                            }

                        case 23:
                            {
                                if (Session.GetHabbo().CurrentRoom.CheckRights(Session, true))
                                {
                                    try
                                    {
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28(uint.Parse(args[1]));
                                        if (ri != null && ri.GetBaseItem().InteractionType == "wf_act_bot_give_handitem")
                                        {
                                            int itemId = 0;
                                            if (int.TryParse(args[2], out itemId))
                                            {
                                                string username = args[3];
                                                RoomUser bot    = null;
                                                foreach (RoomUser ru in Session.GetHabbo().CurrentRoom.RoomUsers)
                                                {
                                                    if (ru != null && ru.IsBot && !ru.IsPet && ru.RoomBot.Name == username)
                                                    {
                                                        bot = ru;
                                                    }
                                                }
                                                if (bot != null)
                                                {
                                                    ri.string_2 = itemId + ";" + username;
                                                }
                                                ri.UpdateState(true, false);
                                            }
                                        }
                                    }
                                    catch { }
                                }
                                break;
                            }

                        case 25:
                            {
                                if (Session.GetHabbo().CurrentRoom.CheckRights(Session, true))
                                {
                                    try
                                    {
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28(uint.Parse(args[1]));
                                        if (ri != null && ri.GetBaseItem().InteractionType == "wf_act_bot_talk" && args[4].Length < 200)
                                        {
                                            string username = args[2];
                                            string type     = (args[3] == "shout" || args[3] == "say") ? args[3] : "say";
                                            string text     = args[4];
                                            RoomUser bot    = null;
                                            foreach (RoomUser ru in Session.GetHabbo().CurrentRoom.RoomUsers)
                                            {
                                                if (ru != null && ru.IsBot && !ru.IsPet && ru.RoomBot.Name == username)
                                                {
                                                    bot = ru;
                                                }
                                            }
                                            if (bot != null)
                                            {
                                                ri.string_2 = username + ";" + type + ";" + text;
                                            }
                                            ri.UpdateState(true, false);
                                        }
                                    }
                                    catch (Exception ex) { Logging.LogException(ex.ToString()); }
                                }
                                break;
                            }

                        case 26:
                            {
                                if (Session.GetHabbo().CurrentRoom.CheckRights(Session, true))
                                {
                                    try
                                    {
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28(uint.Parse(args[1]));
                                        if (ri != null && ri.GetBaseItem().InteractionType == "wf_act_bot_talk_to_avatar" && args[4].Length < 200)
                                        {
                                            string username = args[2];
                                            string type     = (args[3] == "whisper" || args[3] == "say") ? args[3] : "say";
                                            string text     = args[4];
                                            RoomUser bot    = null;
                                            foreach (RoomUser ru in Session.GetHabbo().CurrentRoom.RoomUsers)
                                            {
                                                if (ru != null && ru.IsBot && !ru.IsPet && ru.RoomBot.Name == username)
                                                {
                                                    bot = ru;
                                                }
                                            }
                                            if (bot != null)
                                            {
                                                ri.string_2 = username + ";" + type + ";" + text;
                                            }
                                            ri.UpdateState(true, false);
                                        }
                                    }
                                    catch (Exception ex) { Logging.LogException(ex.ToString()); }
                                }
                                break;
                            }

                        case 28:
                            {
                                if (Session.GetHabbo().CurrentRoom.CheckRights(Session, true))
                                {
                                    try
                                    {
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28(uint.Parse(args[1]));
                                        if (ri != null && ri.GetBaseItem().InteractionType == "wf_act_bot_clothes")
                                        {
                                            string username = args[2];
                                            string newlook  = args[3];
                                            string gender   = args[4];
                                            RoomUser bot    = null;
                                            foreach (RoomUser ru in Session.GetHabbo().CurrentRoom.RoomUsers)
                                            {
                                                if (ru != null && ru.IsBot && !ru.IsPet && ru.RoomBot.Name == username)
                                                {
                                                    bot = ru;
                                                }
                                            }
                                            if (bot != null && AntiMutant.ValidateLook(newlook, gender))
                                            {
                                                ri.string_2 = username + ";" + newlook + ";" + gender;
                                            }
                                            ri.UpdateState(true, false);
                                        }
                                    }
                                    catch { }
                                }
                                break;
                            }

                        case 32:
                            {
                                if (Session.GetHabbo().CurrentRoom.CheckRights(Session, true))
                                {
                                    try
                                    {
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28(uint.Parse(args[1]));
                                        if (ri != null && ri.GetBaseItem().InteractionType == "wf_act_yt")
                                        {
                                            string ytlink = args[2].Split('=')[1];
                                            ri.string_2   = ytlink;
                                            ri.UpdateState(true, false);
                                        }
                                    }
                                    catch { }
                                }
                                break;
                            }

                        case 35:
                            {
                                if (Session.GetHabbo().CurrentRoom.CheckRights(Session, true))
                                {
                                    try
                                    {
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28(uint.Parse(args[1]));
                                        if (ri != null && (ri.GetBaseItem().InteractionType == "wf_cnd_has_purse" || ri.GetBaseItem().InteractionType == "wf_cnd_hasnot_purse"))
                                        {
                                            string currency = Session.GetHabbo().CurrentRoom.IsValidCurrency(args[2]) ? args[2] : "credits";
                                            int number      = 1337;
                                            int.TryParse(args[3], out number);
                                            ri.string_2 = currency + ";" + number;
                                            ri.UpdateState(true, false);
                                        }
                                    }
                                    catch { }
                                }
                                break;
                            }

                        case 36:
                            {
                                if (Session.GetHabbo().CurrentRoom.CheckRights(Session, true))
                                {
                                    try
                                    {
                                        RoomItem ri = Session.GetHabbo().CurrentRoom.method_28(uint.Parse(args[1]));
                                        if (ri != null && ri.GetBaseItem().InteractionType == "wf_act_img" && IsValidFile(args[2]))
                                        {
                                            ri.string_2 = args[2];
                                            ri.UpdateState(true, false);
                                        }
                                    }
                                    catch { }
                                }
                                break;
                            }
                        }
                    }
                };
            });
        }
 public void StartServer()
 {
     WebSocketServer.Start();
 }
Ejemplo n.º 37
0
 /// <summary>
 /// A widget for displaying kingdom lord charts on the dashboard.
 /// </summary>
 /// <param name="server">WebSocket server to send data to.</param>
 /// <param name="version">Mod version.</param>
 public KingdomLordsWidget(WebSocketServer server, Version version)
     : base(server, version)
 {
 }
        public PrinterSocketService(IOptions <AppSettings> appSettings)
        {
            socketServer = new WebSocketServer(appSettings.Value.PrinterSocketPort);

            socketServer.AddWebSocketService <PrinterSocket>("/printer");
        }
Ejemplo n.º 39
0
 public WSServer(string ip)
 {
     wss = new WebSocketServer($"ws://{ip}:9090");
     wss.AddWebSocketService <WSServer>("/");
 }
Ejemplo n.º 40
0
        public static void Init(string ip, int port)
        {
            var server = new WebSocketServer(string.Format("ws://{0}:{1}", ip, port));

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    GameSessionManager.AddSession(GameSession.Parse(socket));
                    WebSocketServerWrappe.OnOpen(socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort);
                };
                socket.OnClose = () =>
                {
                    GameSession session = GameSessionManager.RemoveSession(socket);


                    WebSocketServerWrappe.OnClose(socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort, session.User);
                };
                socket.OnMessage = message =>
                {
                    try
                    {
                        if (message == "ping")
                        {
                            return;
                        }

                        message = Crypto.DESDecrypt(message, DesKey);

                        WebSocketServerWrappe.OnRevice(message);
                        Dictionary <string, string> keyValue = WebSocketPackage.UnPackage(message);

                        if (keyValue == null)
                        {
                            socket.OnError(new Exception("异常包"));
                            return;
                        }

                        ControllerContext context = new ControllerContext(keyValue);
                        context.Session           = GameSessionManager.GetSession(socket);
                        ControllerBase controller = ControllerFactory.CreateController(context);
                        if (controller.IsAuth() && !controller.IsLogin())
                        {
                            if (controller.Login())
                            {
                                byte[] sendByte = controller.ProcessAction();
                                if (sendByte == null)
                                {
                                    return;
                                }
                                List <byte> list = new List <byte>();
                                list.Add((byte)(context.ProtocolId >> 8));
                                list.Add((byte)(context.ProtocolId & 0xFF));
                                list.AddRange(sendByte);
                                WebSocketServerWrappe.OnSend(list.ToArray());
                                socket.Send(list.ToArray());
                            }
                            else
                            {
                                socket.OnError(new Exception("断线重登处理失败"));
                            }
                        }
                        else
                        {
                            byte[] sendByte = controller.ProcessAction();
                            if (sendByte != null)
                            {
                                List <byte> list = new List <byte>();
                                list.Add((byte)(context.ProtocolId >> 8));
                                list.Add((byte)(context.ProtocolId & 0xFF));
                                list.AddRange(sendByte);
                                WebSocketServerWrappe.OnSend(list.ToArray());
                                socket.Send(list.ToArray());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        socket.OnError(ex);
                    }
                };

                socket.OnError = error =>
                {
                    if (!socket.IsAvailable)
                    {
                        socket.OnClose();
                    }
                    else
                    {
                        byte[] array     = WebSocketServerWrappe.OnErrorMessage(error.Message, error);
                        List <byte> list = new List <byte>();
                        list.Add((byte)(9999 >> 8));
                        list.Add((byte)(9999 & 0xFF));
                        list.AddRange(array);
                        socket.Send(list.ToArray());
                    }
                };
            });
        }
Ejemplo n.º 41
0
 public ServerMessageSender(WebSocketServer webSocketServer)
 {
     _webSocketServer = webSocketServer;
 }
Ejemplo n.º 42
0
        public Server()
        {
            Console.Write("Server started\n");

            m_Clients = new Dictionary <IWebSocketConnection, Client>();
            m_Socket  = new WebSocketServer($"ws://0.0.0.0:1000");
            ServerResponse response = new ServerResponse();

            m_Socket.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console
                    .WriteLine($"[Client: connected] " +
                               $"{socket.ConnectionInfo.ClientIpAddress}");
                };

                socket.OnMessage = (string message) =>
                {
                    var request = Json.FromJson <ClientRequest>(message);

                    switch (request.Operation)
                    {
                    case OperationType.Login:
                        {
                            if (m_Clients.ContainsValue(request.Client))
                            {
                                return;
                            }

                            m_Clients.Add(socket, request.Client);
                            response.Message      = $"{request.Client.Nickname} connected to chat!";
                            response.ResponseType = ResponseType.Login;
                            foreach (var client in m_Clients)
                            {
                                if (client.Value.Nickname != request.Client.Nickname)
                                {
                                    client.Key.Send(response.ToJson());
                                }
                            }
                        }
                        break;

                    case OperationType.Logout:
                        {
                            lock (sync)
                            {
                                socket.Close();
                                m_Clients.Remove(socket);
                            }
                        }
                        break;

                    case OperationType.PostMessage:
                        {
                            string messageToSend =
                                $"{request.Client.Nickname}: " +
                                $"{request.Client.Message}";
                            response.Message      = messageToSend;
                            response.ResponseType = ResponseType.Message;
                            foreach (var client in m_Clients)
                            {
                                if (client.Value.Nickname != request.Client.Nickname)
                                {
                                    client.Key.Send(response.ToJson());
                                }
                            }
                        }
                        break;

                    default:
                        //Console.WriteLine(message);
                        break;
                    }
                };

                socket.OnError = (Exception exception) =>
                {
                    lock (sync)
                    {
                        Console
                        .WriteLine($"[Error: client disconnected] " +
                                   $"{socket.ConnectionInfo.ClientIpAddress}");
                        if (m_Clients.ContainsKey(socket))
                        {
                            var clientToDelete    = m_Clients[socket];
                            response.Message      = $"{clientToDelete.Nickname} disconnected from chat!";
                            response.ResponseType = ResponseType.Logout;
                            m_Clients.Remove(socket);
                            foreach (var client in m_Clients)
                            {
                                client.Key.Send(response.ToJson());
                            }
                        }
                    }
                };

                socket.OnClose = () =>
                {
                    lock (sync)
                    {
                        Console
                        .WriteLine($"[Client: disconnected] " +
                                   $"{socket.ConnectionInfo.ClientIpAddress}");

                        if (m_Clients.ContainsKey(socket))
                        {
                            //handling disconnecting of client
                        }
                    }
                };
            });
        }
Ejemplo n.º 43
0
 private Server(int port)
 {
     WebSocket   = new WebSocketServer(port);
     AuthHandler = new AuthHandler();
 }
Ejemplo n.º 44
0
        private static async Task RunCommand(Options options, bool noOptions)
        {
            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.

            //ManualResetEvent exitMre = new ManualResetEvent(false);

            logger = AddConsoleLogger();

            // Start MDNS server.
            var mdnsServer = new ServiceDiscovery();

            if (options.StunServer != null)
            {
                string[] fields = options.StunServer.Split(';');

                _stunServer = new RTCIceServer
                {
                    urls           = fields[0],
                    username       = fields.Length > 1 ? fields[1] : null,
                    credential     = fields.Length > 2 ? fields[2] : null,
                    credentialType = RTCIceCredentialType.password
                };
            }

            _relayOnly = options.RelayOnly;

            if (!string.IsNullOrEmpty(options.IceTypes))
            {
                options.IceTypes.Split().ToList().ForEach(x =>
                {
                    if (Enum.TryParse <RTCIceCandidateType>(x, out var iceType))
                    {
                        _iceTypes.Add(iceType);
                    }
                });

                if (!_iceTypes.Any(x => x == RTCIceCandidateType.host))
                {
                    _offerOptions = new RTCOfferOptions {
                        X_ExcludeIceCandidates = true
                    };
                    _answerOptions = new RTCAnswerOptions {
                        X_ExcludeIceCandidates = true
                    };
                }
            }

            if (!string.IsNullOrEmpty(options.AcceptIceTypes))
            {
                options.AcceptIceTypes.Split().ToList().ForEach(x =>
                {
                    if (Enum.TryParse <RTCIceCandidateType>(x, out var iceType))
                    {
                        _acceptIceTypes.Add(iceType);
                    }
                });
            }

            if (options.UseWebSocket || options.UseSecureWebSocket || noOptions)
            {
                // Start web socket.
                Console.WriteLine("Starting web socket server...");
                _webSocketServer = new WebSocketServer(IPAddress.Any, WEBSOCKET_PORT, options.UseSecureWebSocket);
                if (options.UseSecureWebSocket)
                {
                    _webSocketServer.SslConfiguration.ServerCertificate          = new X509Certificate2(LOCALHOST_CERTIFICATE_PATH);
                    _webSocketServer.SslConfiguration.CheckCertificateRevocation = false;
                }
                _webSocketServer.AddWebSocketService <WebRTCWebSocketPeer>("/", (peer) =>
                {
                    peer.OfferOptions = _offerOptions;
                    if (_acceptIceTypes != null && _acceptIceTypes.Count > 0)
                    {
                        peer.FilterRemoteICECandidates = (init) => _acceptIceTypes.Any(x => x == RTCIceCandidate.Parse(init.candidate).type);
                    }
                    peer.CreatePeerConnection = CreatePeerConnection;
                });
                _webSocketServer.Start();

                Console.WriteLine($"Waiting for browser web socket connection to {_webSocketServer.Address}:{_webSocketServer.Port}...");
            }
            else if (!string.IsNullOrWhiteSpace(options.WebSocketServer))
            {
                // We are the client for a web socket server. The JSON signalling exchange still occurs the same way as when the web socket
                // server option is used except that as the web socket client we receive the SDP offer from the server.
                WebRTCWebSocketClient wsockClient = new WebRTCWebSocketClient(options.WebSocketServer, CreatePeerConnection);
                await wsockClient.Start(exitCts.Token);

                Console.WriteLine("web socket client started.");
            }
            else if (options.CreateJsonOffer)
            {
                var pc = await Createpc(null, _stunServer, _relayOnly);

                var offerSdp = pc.createOffer(null);
                await pc.setLocalDescription(offerSdp);

                Console.WriteLine(offerSdp.sdp);

                var offerJson   = JsonConvert.SerializeObject(offerSdp, new Newtonsoft.Json.Converters.StringEnumConverter());
                var offerBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(offerJson));

                Console.WriteLine(offerBase64);

                string remoteAnswerB64 = null;
                while (string.IsNullOrWhiteSpace(remoteAnswerB64))
                {
                    Console.Write("Remote Answer => ");
                    remoteAnswerB64 = Console.ReadLine();
                }

                string remoteAnswer = Encoding.UTF8.GetString(Convert.FromBase64String(remoteAnswerB64));

                Console.WriteLine(remoteAnswer);

                RTCSessionDescriptionInit answerInit = JsonConvert.DeserializeObject <RTCSessionDescriptionInit>(remoteAnswer);

                Console.WriteLine($"Remote answer: {answerInit.sdp}");

                var res = pc.setRemoteDescription(answerInit);
                if (res != SetDescriptionResultEnum.OK)
                {
                    // No point continuing. Something will need to change and then try again.
                    pc.Close("failed to set remote sdp");
                }
            }
            else if (options.NodeDssServer != null)
            {
                string[] fields = options.NodeDssServer.Split(';');
                if (fields.Length < 3)
                {
                    throw new ArgumentException("The 'nodedss' option must contain 3 semi-colon separated fields, e.g. --nodedss=http://127.0.0.1:3000;myid;theirid.");
                }

                var nodeDssPeer = new WebRTCNodeDssPeer(fields[0], fields[1], fields[2], CreatePeerConnection);
                await nodeDssPeer.Start(exitCts);
            }

            _ = Task.Run(() => ProcessInput(exitCts));

            // Ctrl-c will gracefully exit the call at any point.
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                exitCts.Cancel();
            };

            // Wait for a signal saying the call failed, was cancelled with ctrl-c or completed.
            exitCts.Token.WaitHandle.WaitOne();

            Console.WriteLine();
            Console.WriteLine("Exiting...");

            _peerConnection?.Close("application exit");

            _webSocketServer?.Stop();

            Task.Delay(1000).Wait();
        }
Ejemplo n.º 45
0
 public AppConnectionHandler(WebSocketServer ws)
 {
     WebSocketServer = ws;
 }
Ejemplo n.º 46
0
 void OnDestroy()
 {
     server.Stop();
     server = null;
 }
Ejemplo n.º 47
0
        public static void Main(string[] args)
        {
            /* Create a new instance of the WebSocketServer class.
             *
             * If you would like to provide the secure connection, you should create the instance with
             * the 'secure' parameter set to true, or the wss scheme WebSocket URL.
             */
            var wssv = new WebSocketServer(4649);

            //var wssv = new WebSocketServer (5963, true);
            //var wssv = new WebSocketServer (System.Net.IPAddress.Parse ("127.0.0.1"), 4649);
            //var wssv = new WebSocketServer (System.Net.IPAddress.Parse ("127.0.0.1"), 5963, true);
            //var wssv = new WebSocketServer ("ws://localhost:4649");
            //var wssv = new WebSocketServer ("wss://localhost:5963");
#if DEBUG
            // To change the logging level.
            wssv.Log.Level = LogLevel.Trace;

            // To change the wait time for the response to the WebSocket Ping or Close.
            wssv.WaitTime = TimeSpan.FromSeconds(2);
#endif

            /* To provide the secure connection.
             * var cert = ConfigurationManager.AppSettings["ServerCertFile"];
             * var passwd = ConfigurationManager.AppSettings["CertFilePassword"];
             * wssv.SslConfiguration.ServerCertificate = new X509Certificate2 (cert, passwd);
             */

            /* To provide the HTTP Authentication (Basic/Digest).
             * wssv.AuthenticationSchemes = AuthenticationSchemes.Basic;
             * wssv.Realm = "WebSocket Test";
             * wssv.UserCredentialsFinder = id => {
             * var name = id.Name;
             *
             * // Return user name, password, and roles.
             * return name == "nobita"
             *       ? new NetworkCredential (name, "password", "gunfighter")
             *       : null; // If the user credentials aren't found.
             * };
             */

            // Not to remove the inactive sessions periodically.
            //wssv.KeepClean = false;

            // To resolve to wait for socket in TIME_WAIT state.
            //wssv.ReuseAddress = true;

            // Add the WebSocket services.
            wssv.AddWebSocketService <Echo> ("/Echo");
            wssv.AddWebSocketService <Chat> ("/Chat");

            /* Add the WebSocket service with initializing.
             * wssv.AddWebSocketService<Chat> (
             * "/Chat",
             * () => new Chat ("Anon#") {
             *  Protocol = "chat",
             *  // To ignore the Sec-WebSocket-Extensions header.
             *  IgnoreExtensions = true,
             *  // To validate the Origin header.
             *  OriginValidator = val => {
             *    // Check the value of the Origin header, and return true if valid.
             *    Uri origin;
             *    return !val.IsNullOrEmpty () &&
             *           Uri.TryCreate (val, UriKind.Absolute, out origin) &&
             *           origin.Host == "localhost";
             *  },
             *  // To validate the Cookies.
             *  CookiesValidator = (req, res) => {
             *    // Check the Cookies in 'req', and set the Cookies to send to the client with 'res'
             *    // if necessary.
             *    foreach (Cookie cookie in req) {
             *      cookie.Expired = true;
             *      res.Add (cookie);
             *    }
             *
             *    return true; // If valid.
             *  }
             * });
             */

            wssv.Start();
            if (wssv.IsListening)
            {
                Console.WriteLine("Listening on port {0}, and providing WebSocket services:", wssv.Port);
                foreach (var path in wssv.WebSocketServices.Paths)
                {
                    Console.WriteLine("- {0}", path);
                }
            }

            Console.WriteLine("\nPress Enter key to stop the server...");
            Console.ReadLine();

            wssv.Stop();
        }
Ejemplo n.º 48
0
        private void Loop_WSS()
        {
            Task.Run(async() =>
            {
                Dispatcher.Invoke(() =>
                {
                    WebSocketServerStatus.Inlines.Clear();
                    WebSocketServerStatus.Inlines.Add(new Run("WebSocket Server\n")
                    {
                        FontWeight = FontWeights.Bold
                    });
                    WebSocketServerStatus.Inlines.Add(new Run("Starting up...\n"));
                    WebSocketServerStatus.Inlines.Add(new Run("...")
                    {
                        FontSize = 26
                    });
                });

                await Task.Delay(3000);
                while (!online)
                {
                    await Task.Delay(5000); Dispatcher.Invoke(() => { ExchangeRateInfo.Text = $"WSSV awaits Internet ..."; });
                }

                WSSV = new WebSocketServer(WSSPORT);
                WSSV.AddWebSocketService(WSSENDPOINT, () => new WSS_Behavior(this));
                WSSV.Start();

                while (!WSSV.IsListening)
                {
                    await Task.Delay(5000); Dispatcher.Invoke(() => { ExchangeRateInfo.Text = $"WSSV awaits startup ..."; });
                }
                log.Information("Websocket Server running.");

                while (true)
                {
                    Activity();

                    try
                    {
                        await Task.Run(() =>
                        {
                            Dispatcher.Invoke(() =>
                            {
                                WebSocketServerStatus.Inlines.Clear();
                                WebSocketServerStatus.Inlines.Add(new Run("WebSocket Server\n")
                                {
                                    FontWeight = FontWeights.Bold
                                });
                                WebSocketServerStatus.Inlines.Add(new Run("ws://" + Dns.GetHostEntry(Dns.GetHostName()).AddressList.First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString() + ":" + WSSV.Port.ToString() + WSSENDPOINT + "\n")
                                {
                                    FontSize = 9
                                });
                                WebSocketServerStatus.Inlines.Add(new Run(WSSV.WebSocketServices.SessionCount.ToString())
                                {
                                    FontSize = 26
                                });
                            });

                            WSSV.WebSocketServices.Broadcast(JsonConvert.SerializeObject(new WSS_Communication()
                            {
                                info              = WSS_Communication.ExRateInfoType.Rates,
                                success           = true,
                                currencies        = Currencies,
                                currencies_change = Change?.Union(Change_Specific).ToList(),
                                rates             = Rates?.ToList(),
                            }));
                        });
                    }
                    catch (Exception ex)
                    {
                        log.Error($"Error in Websocket Server Loop: {ex.Message} {ex}");
                    }
                    finally
                    {
                        await Task.Delay(3000);
                    }
                }
            });
        }
Ejemplo n.º 49
0
        private static async Task <bool> TwitchLogin()
        {
            string twitchUsername = null;
            string twitchOAuth    = null;
            string twitchPollPass = null;

            m_twitchPollMode = File.Exists("chaosmod/.twitchpoll");

            OptionsFile twitchFile = new OptionsFile("chaosmod/twitch.ini");

            twitchFile.ReadFile();

            m_twitchChannelName                    = twitchFile.ReadValue("TwitchUserName");
            twitchUsername                         = twitchFile.ReadValue("TwitchChannelName");
            twitchOAuth                            = twitchFile.ReadValue("TwitchChannelOAuth");
            twitchPollPass                         = twitchFile.ReadValue("TwitchVotingPollPass");
            m_disableNoVoteMsg                     = twitchFile.ReadValueBool("TwitchVotingDisableNoVoteRoundMsg", false);
            m_enableTwitchChanceSystem             = twitchFile.ReadValueBool("TwitchVotingChanceSystem", false);
            m_enableTwitchChanceSystemRetainChance = twitchFile.ReadValueBool("TwitchVotingChanceSystemRetainChance", true);

            if (m_twitchPollMode)
            {
                OptionsFile configFile = new OptionsFile("chaosmod/config.ini");
                configFile.ReadFile();

                m_twitchPollDur = twitchFile.ReadValueInt("NewEffectSpawnTime", 30);

                if (m_twitchPollDur < 15 || m_twitchPollDur > 180)
                {
                    SendToPipe("invalid_poll_dur");

                    return(false);
                }
            }

            if (m_twitchPollMode)
            {
                m_twitchPollClients = new List <IWebSocketConnection>();

                m_twitchSocketServer = new WebSocketServer("ws://0.0.0.0:31337");
                m_twitchSocketServer.RestartAfterListenError = true;
                m_twitchSocketServer.Start(socket =>
                {
                    socket.OnOpen += () =>
                    {
                        Console.WriteLine($"New client! ({socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort})");

                        socket.Send($"{{\"type\":\"auth\",\"data\":\"{twitchPollPass}\"}}");

                        m_twitchPollClients.Add(socket);
                    };

                    socket.OnMessage += (msg) =>
                    {
                        Console.WriteLine(msg);

                        dynamic json = DeserializeJson(msg);
                        if (json == null)
                        {
                            return;
                        }

                        string type = json.type;

                        if (type == "created")
                        {
                            m_twitchPollUUID = json.id;
                        }
                        else if (type == "update")
                        {
                            dynamic choices = json.poll.choices;

                            m_votes[0] = (int)choices[0].votes;
                            m_votes[1] = (int)choices[1].votes;
                            m_votes[2] = (int)choices[2].votes;

                            m_twitchPollUUID = null;
                        }
                    };

                    socket.OnClose += () =>
                    {
                        Console.WriteLine($"Connection to client {socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort} closed.");

                        m_twitchPollClients.Remove(socket);
                    };
                });

                return(true);
            }

            if (string.IsNullOrWhiteSpace(m_twitchChannelName) || string.IsNullOrWhiteSpace(twitchUsername) || string.IsNullOrWhiteSpace(twitchOAuth))
            {
                SendToPipe("invalid_login");

                return(false);
            }

            ConnectionCredentials credentials     = new ConnectionCredentials(twitchUsername, twitchOAuth);
            WebSocketClient       webSocketClient = new WebSocketClient();

            m_twitchClient = new TwitchClient(webSocketClient);
            m_twitchClient.Initialize(credentials, m_twitchChannelName);

            m_twitchClient.OnMessageReceived += OnMessageRecieved;

            bool failed = false;
            bool done   = false;

            m_twitchClient.OnConnectionError += (object sender, OnConnectionErrorArgs e) =>
            {
                failed = true;
                done   = true;
            };

            m_twitchClient.OnConnected += (object sender, OnConnectedArgs e) =>
            {
                done = true;
            };

            m_twitchClient.Connect();

            int lastTick = Environment.TickCount;

            while (!done)
            {
                await Task.Delay(100);

                if (lastTick < Environment.TickCount - 3000)
                {
                    failed = true;
                    done   = true;

                    break;
                }
            }

            if (failed)
            {
                SendToPipe("invalid_login");

                return(false);
            }

            Console.WriteLine("Logged into Twitch Account!");

            done = false;

            m_twitchClient.OnJoinedChannel += (object sender, OnJoinedChannelArgs e) =>
            {
                if (e.Channel.ToLower() == m_twitchChannelName.ToLower())
                {
                    done = true;
                }
            };

            lastTick = Environment.TickCount;
            while (!done)
            {
                await Task.Delay(100);

                if (lastTick < Environment.TickCount - 1500)
                {
                    failed = true;
                    done   = true;
                }
            }

            if (failed)
            {
                SendToPipe("invalid_channel");

                return(false);
            }

            Console.WriteLine("Connected to Twitch Channel!");

            return(true);
        }
Ejemplo n.º 50
0
 public MainWindow()
 {
     InitializeComponent();
     webServer = new WebSocketServer(9999);
     webServer.AddWebSocketService <Echo>("/Echo");
 }
Ejemplo n.º 51
0
        static void Main()
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List <IWebSocketConnection>();
            var server     = new WebSocketServer("ws://0.0.0.0:8181");

            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    allSockets.Add(socket);
                }; // End OnOpen

                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    allSockets.Remove(socket);
                }; // End OnClose

                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    //allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                    Comunicacion oMessage = JsonConvert.DeserializeObject <Comunicacion>(message);
                    cmh.SubEvento         = oMessage.SubEvento;
                    cmh.FEN       = oMessage.FEN;
                    cmh.Segundos  = oMessage.Segundos;
                    cmh.MultiPv   = oMessage.MultiPv;
                    cmh.webSocket = socket;

                    int Milisegundos = System.Convert.ToInt32(oMessage.Segundos);
                    Milisegundos     = Milisegundos * 1000;

                    if (oMessage.SubEvento == "Calcular")
                    {
                        cmh.process.StandardInput.WriteLine("setoption name multipv value " + oMessage.MultiPv);
                        cmh.process.StandardInput.Flush();

                        cmh.process.StandardInput.WriteLine("position fen " + oMessage.FEN);
                        cmh.process.StandardInput.Flush();

                        cmh.process.StandardInput.WriteLine("go movetime " + Milisegundos.ToString());
                        cmh.process.StandardInput.Flush();
                    }

                    if (oMessage.SubEvento == "Reset")
                    {
                        cmh.process.StandardInput.WriteLine("stop");
                        cmh.process.StandardInput.Flush();

                        //cmh.process.StandardInput.WriteLine("go movetime 15000");
                        //cmh.process.StandardInput.Flush();
                    }

                    if (oMessage.SubEvento == "Conectar")
                    {
                        // Creamos un delegado para el método OutListText()
                        ThreadStart ts = new ThreadStart(cmh.OutListText);

                        // Creamos un hilo para ejecutar el delegado...
                        Thread t = new Thread(ts);

                        t.Start();

                        Thread.Sleep(2000);

                        cmh.webSocket.Send("Conectado");

                        //cmh.process.StandardInput.WriteLine("stop");
                        //cmh.process.StandardInput.Flush();
                    }
                }; // End OnMessage
            });

            var input = Console.ReadLine();

            while (input != "exit")
            {
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }
Ejemplo n.º 52
0
        static void Main()
        {
            if (!File.Exists(Global.DEFAULT_PATH))
            {
                Directory.CreateDirectory(Global.DEFAULT_FOLDER);

                using (FileStream fs = File.Create(Global.DEFAULT_PATH)) {
                    byte[] info = new System.Text.UTF8Encoding(true).GetBytes("0.0.0.0:25565");
                    fs.Write(info, 0, info.Length);
                }
            }

            string ip = "";

            if (File.Exists(Global.DEFAULT_PATH))
            {
                using (StreamReader sr = File.OpenText(Global.DEFAULT_PATH)) {
                    ip = sr.ReadLine();
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var server = new WebSocketServer("ws://" + ip);

            RefreshApps();

            server.Start(socket => {
                socket.OnOpen  = () => RefreshApps();
                socket.OnClose = () => RefreshApps();

                socket.OnMessage = message => {
                    if (message.StartsWith("VOLUME"))
                    {
                        ChangeVolume(message.Split(':')[1], float.Parse(message.Split(':')[2]));
                    }

                    if (message.StartsWith("MUTE"))
                    {
                        ChangeState(message.Split(':')[1], message.Split(':')[0]);
                    }

                    if (message.StartsWith("UNMUTE"))
                    {
                        ChangeState(message.Split(':')[1], message.Split(':')[0]);
                    }

                    if (message.StartsWith("INFO"))
                    {
                        string to_send = "{\"info\":{\"computer\":\"" + Global.COMPUTER_NAME + "\"}}";

                        socket.Send(to_send);
                    }

                    if (message.StartsWith("APPS"))
                    {
                        RefreshApps();

                        string to_send = "{\"apps\":{";

                        foreach (KeyValuePair <string, SoundApplication> entry in applications)
                        {
                            to_send += "\"" + entry.Key + "\":\"" + entry.Value.Volume + "\",";
                        }

                        to_send  = to_send.Remove(to_send.Length - 1);
                        to_send += "}}";

                        socket.Send(to_send);
                    }
                };
            });

            Application.Run(new DefaultApp());
        }
Ejemplo n.º 53
0
 protected override void OnBeginService(int Address)
 {
     wss = new WebSocketServer();
     wss.Listen(Address);
 }
Ejemplo n.º 54
0
    public BaseServer()
    {
        // Whether we should use SSL.
        // This is true if we are running in production mode or if the setting to use SSL only in production mode is
        // deactivated
        var secure = !ServerSettings.Instance.UseSslOnlyInProductionMode || !DebugSettings.Instance.DebugMode;

        // Whether to run a full HTTP server or websockets only
        // This is true if we are running in production mode or if the setting to use HTTP only in production mode is
        // deactivated
        var runHttpServer = !ServerSettings.Instance.RunHttpServerOnlyInProductionMode ||
                            !DebugSettings.Instance.DebugMode;

        // Determine the protocol depending on the above flags
        // E.g. http(s) or ws(s)
        _usedProtocol = runHttpServer ? (secure ? "https" : "http") : (secure ? "wss" : "ws");

        // Determine the port to use. If we are running in websocket-only mode, we use a different port so that the
        // replacement HTTP server for development can listen to the main port.
        _usedPort = runHttpServer ? ServerSettings.Instance.ControllerAppPort : ServerSettings.Instance.WebsocketPort;

        // Construct the server URL from the above flags
        // E.g. https://0.0.0.0:8000 or ws://0.0.0.0:4242
        _url = $"{_usedProtocol}://{Address}:{_usedPort}";

        // Construct websocket-only server, if running in websocket-only (debug) mode
        if (!runHttpServer)
        {
            Log(
                "Using web socket server only (because we are running in debug/development mode). Use a separate web server to server the controller software and a proxy to redirect websocket traffic here.");
            _wss = new WebSocketServer(_url);

            // If SSL shall be used, configure the server to use the certificate
            if (secure)
            {
                Log("Using SSL.");
                _wss.SslConfiguration.ServerCertificate = ServerSettings.Instance.RetrieveCertificate();
            }

            else
            {
                Log("Using *NO* SSL.");
            }
        }

        // Otherwise, construct a server which can serve documents over HTTP and websoockets...
        else
        {
            var documentRoot =
                $"{PathUtils.GetInstallDirectory()}/{ServerSettings.Instance.ControllerAppDocumentRoot}";

            Log(
                $"Serving websockets and web content on single port. Using the following document root: {documentRoot}");
            _httpServerBackend = new WebSocketSharp.Server.HttpServer(_url);

            if (DebugSettings.Instance.DebugMode)
            {
                _httpServerBackend.Log.Level = LogLevel.Trace;
            }

            _httpServerBackend.DocumentRootPath = documentRoot;

            if (secure)
            {
                Log("Using SSL.");
                _httpServerBackend.SslConfiguration.ServerCertificate = ServerSettings.Instance.RetrieveCertificate();
            }

            _httpServerBackend.OnGet += this.OnHTTPGet;
        }
    }
Ejemplo n.º 55
0
 public SocketServer(int port = 8888)
 {
     server = new WebSocketServer(port);
 }
Ejemplo n.º 56
0
        private static void Main(string[] args)
        {
            // Are we running yet?

            if (!SystemSettings.DatabaseInitialized)
            {
                // will restart the service every 15s until db initialized on OOBE
                // also, the read of DatabaseInitialized can and will fail if
                // we're not initalized enough to even have a database

                throw new InvalidOperationException();
            }

            // Checking for schemata upgrade first of all, after seeing that db exists

            int startupDbVersion = Database.SwarmDb.DbVersion;

            DatabaseMaintenance.UpgradeSchemata();

            testMode = false;

            SystemSettings.BackendHostname = Dns.GetHostName();


            // Other one-time initializations

            FinancialTransactions.FixAllUnsequenced();
            SupportFunctions.OperatingTopology = OperatingTopology.Backend;

            // Begin main loop

            UnixSignal[] killSignals = null;

            if (!Debugger.IsAttached)
            {
                killSignals = new UnixSignal[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) };
            }

            BotLog.Write(0, "MainCycle", string.Empty);
            BotLog.Write(0, "MainCycle", "-----------------------------------------------");
            BotLog.Write(0, "MainCycle", string.Empty);

            if (args.Length > 0)
            {
                if (args[0].ToLower() == "test")
                {
                    BotLog.Write(0, "MainCycle", "Running self-tests");

                    testMode = true;
                    Console.WriteLine("Testing All Maintenance Processes (except membership-changing ones).");

                    Console.WriteLine("\r\n10-second intervals:");
                    OnEveryTenSeconds();
                    Console.WriteLine("\r\nEvery minute:");
                    OnEveryMinute();
                    Console.WriteLine("\r\nEvery five minutes:");
                    OnEveryFiveMinutes();
                    Console.WriteLine("\r\nEvery hour:");
                    OnEveryHour();
                    Console.WriteLine("\r\nNoon:");
                    OnNoon();
                    Console.WriteLine("\r\nMidnight:");
                    OnMidnight();
                    Console.WriteLine("\r\nMonday Morning:");
                    OnMondayMorning();

                    Console.WriteLine("\r\nTesting database access...");

                    Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).Name);
                    Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).PasswordHash);

                    Console.WriteLine("Creating OutboundComm...");

                    OutboundComm.CreateNotification(null, NotificationResource.System_Startup_Backend);

                    Console.WriteLine("Transmitting...");

                    OutboundComms comms = OutboundComms.GetOpen();

                    Console.WriteLine("{0} open items in outbound comms.", comms.Count);

                    foreach (OutboundComm comm in comms)
                    {
                        if (comm.TransmitterClass != "Swarmops.Utility.Communications.CommsTransmitterMail")
                        {
                            throw new NotImplementedException();
                        }

                        ICommsTransmitter transmitter = new CommsTransmitterMail();

                        OutboundCommRecipients recipients = comm.Recipients;
                        PayloadEnvelope        envelope   = PayloadEnvelope.FromXml(comm.PayloadXml);

                        foreach (OutboundCommRecipient recipient in recipients)
                        {
                            transmitter.Transmit(envelope, recipient.Person);
                        }
                    }


                    Console.Write("\r\nAll tests run. Waiting for mail queue to flush... ");
                    while (!MailTransmitter.CanExit)
                    {
                        Thread.Sleep(50);
                    }

                    Console.WriteLine("done.");
                    BotLog.Write(0, "MainCycle", "Exiting self-tests");
                    return;
                }

                if (args[0].ToLower() == "console")
                {
                    Console.WriteLine("\r\nRunning Swarmops-Backend in CONSOLE mode.\r\n");

                    // -------------------------------------------------------------------------------------
                    // -------------------------------------------------------------------------------------
                    // -------------------------------------------------------------------------------------

                    // -----------------------    INSERT ANY ONE-OFF ACTIONS HERE  -------------------------


                    Console.Write("\r\nWaiting for mail queue to flush... ");

                    while (!MailTransmitter.CanExit)
                    {
                        Thread.Sleep(50);
                    }

                    Console.WriteLine("done.");

                    return;
                }

                if (args[0].ToLowerInvariant() == "pdfregen")
                {
                    if (args.Length > 1)
                    {
                        int docId = Int32.Parse(args[1]);
                        PdfProcessor.Rerasterize(Document.FromIdentity(docId));
                    }
                    else
                    {
                        Console.WriteLine("Regenerating all bitmaps from PDF uploads.");
                        PdfProcessor.RerasterizeAll();
                        Console.WriteLine("Done.");
                    }

                    return;
                }


                if (args[0].ToLower() == "rsm")
                {
                    Console.WriteLine("Testing character encoding: räksmörgås RÄKSMÖRGÅS");
                    return;
                }
            }

            /*
             * MailMessage message = new MailMessage();
             * message.From = new MailAddress(Strings.MailSenderAddress, Strings.MailSenderName);
             * message.To.Add (new MailAddress ("*****@*****.**", "Rick Falkvinge (Piratpartiet)"));
             * message.Subject = "Räksmörgåsarnas ékÖNÖMÏåvdëlnïng";
             * message.Body = "Hejsan hoppsan Räksmörgåsar.";
             * message.BodyEncoding = Encoding.Default;
             * message.SubjectEncoding = Encoding.Default;
             *
             * SmtpClient smtpClient = new SmtpClient ("localhost");
             * smtpClient.Credentials = null; // mono bug
             * smtpClient.Send (message);*/

            Console.WriteLine(" * Swarmops Backend starting");

            BotLog.Write(0, "MainCycle", "Backend STARTING");

            // Disable certificate checking due to Mono not installing with a certificate repository - this is UTTERLY broken

            SupportFunctions.DisableSslCertificateChecks(); // MONO BUG/MISFEATURE: Mono has no root certificates, so can't verify cert

            // Tell sysop we're starting

            OutboundComm.CreateNotification(null, NotificationResource.System_Startup_Backend);

            // Check for existence of installation ID. If not, create one. Warning: has privacy implications when communicated.

            if (Persistence.Key["SwarmopsInstallationId"] == string.Empty)
            {
                Persistence.Key["SwarmopsInstallationId"] = Guid.NewGuid().ToString();
            }

            // Check for existence of bitcoin hotwallet root

            BitcoinUtility.VerifyBitcoinHotWallet();

            // Initialize backend socket server

            int backendSocketPort = SystemSettings.WebsocketPortBackend;

            _socketServer = new WebSocketServer(backendSocketPort);
            _socketServer.AddWebSocketService <BackendServices>("/Backend");
            _socketServer.Start();

            // Initialize socket client to Blockchain.Info (pending our own services)

            using (
                _blockChainInfoSocket =
                    new WebSocket("wss://ws.blockchain.info/inv?api_code=" + SystemSettings.BlockchainSwarmopsApiKey))
            {
                // Begin maintenance loop

                DateTime cycleStartTime = DateTime.UtcNow;
                DateTime cycleEndTime;

                int lastSecond = cycleStartTime.Second;
                int lastMinute = cycleStartTime.Minute;
                int lastHour   = cycleStartTime.Hour;

                bool exitFlag = false;

                _blockChainInfoSocket.OnOpen    += new EventHandler(OnBlockchainOpen);
                _blockChainInfoSocket.OnError   += new EventHandler <ErrorEventArgs>(OnBlockchainError);
                _blockChainInfoSocket.OnClose   += new EventHandler <CloseEventArgs>(OnBlockchainClose);
                _blockChainInfoSocket.OnMessage += new EventHandler <MessageEventArgs>(OnBlockchainMessage);

                _blockChainInfoSocket.Connect();

                while (!exitFlag) // exit is handled by signals handling at end of loop
                {
                    BotLog.Write(0, "MainCycle", "Cycle Start");

                    cycleStartTime = DateTime.UtcNow;
                    cycleEndTime   = cycleStartTime.AddSeconds(10);

                    try
                    {
                        OnEveryTenSeconds();

                        if (cycleStartTime.Second < lastSecond)
                        {
                            OnEveryMinute();

                            if (cycleStartTime.Minute % 5 == 0)
                            {
                                OnEveryFiveMinutes();
                            }
                        }

                        if (cycleStartTime.Minute < lastMinute)
                        {
                            OnEveryHour();

                            if (DateTime.Now.Hour == 10 && DateTime.Today.DayOfWeek == DayOfWeek.Tuesday)
                            {
                                OnTuesdayMorning();
                            }

                            if (DateTime.Now.Hour == 7 && DateTime.Today.DayOfWeek == DayOfWeek.Monday)
                            {
                                OnMondayMorning();
                            }
                        }

                        if (cycleStartTime.Hour >= 12 && lastHour < 12)
                        {
                            OnNoon();
                        }

                        if (cycleStartTime.Hour < lastHour)
                        {
                            OnMidnight();
                        }
                    }

                    catch (Exception e)
                    {
                        // Note each "OnEvery..." catches its own errors and sends Exception mails,
                        // so that failure in one should not stop the others from running. This particular
                        // code should never run.

                        ExceptionMail.Send(new Exception("Failed in swarmops-backend main loop", e), true);
                    }

                    lastSecond = cycleStartTime.Second;
                    lastMinute = cycleStartTime.Minute;
                    lastHour   = cycleStartTime.Hour;

                    // Wait for a maximum of ten seconds (the difference between cycleStartTime and cycleEndTime)

                    int      iterationCount = 0;
                    DateTime utcNow         = DateTime.UtcNow;
                    while (utcNow < cycleEndTime && !exitFlag)
                    {
                        int signalIndex = 250;

                        // Handle important service orders (those that can't be lost in a random loss
                        // of connection of a socket):

                        BackendServiceOrders backendOrders = BackendServiceOrders.GetNextBatch(5);
                        backendOrders.Execute(); // takes at most 250ms per BSO reqs

                        // Block until a SIGINT or SIGTERM signal is generated, or 1/4 second has passed.
                        // However, we can't do that in a development environment - it won't have the
                        // Mono.Posix assembly, and won't understand UnixSignals. So people running this in
                        // a dev environment will need to stop it manually.

                        if (!Debugger.IsAttached)
                        {
                            signalIndex = UnixSignal.WaitAny(killSignals, 250);
                        }
                        else
                        {
                            TimeSpan timeLeft = (cycleEndTime - utcNow);

                            BotLog.Write(0, "MainCycle Debug",
                                         string.Format(CultureInfo.InvariantCulture,
                                                       "Waiting for {0:F2} more seconds for cycle end",
                                                       timeLeft.TotalMilliseconds / 1000.0));
                            Thread.Sleep(250);
                        }

                        if (signalIndex < 250)
                        {
                            exitFlag = true;
                            Console.WriteLine("Caught signal " + killSignals[signalIndex].Signum + ", exiting");
                            BotLog.Write(0, "MainCycle",
                                         "EXIT SIGNAL (" + killSignals[signalIndex].Signum + "), terminating backend");
                        }

                        utcNow = DateTime.UtcNow;

                        // Every second, send an internal heartbeat

                        if (iterationCount++ % 4 == 0)
                        {
                            InternalHeartbeat();
                        }
                    }
                }
            }

            Console.WriteLine(" * Swarmops Backend stopping");
            BotLog.Write(0, "MainCycle", "BACKEND EXITING, sending backend-termination notices");

            /*
             * if (HeartBeater.Instance.WasKilled)
             * {
             *  // removed unconditional delete, cron job that restarts bot uses it to know that it is intentionally down.
             *  ExceptionMail.Send(new Exception("HeartBeater triggered restart of Swarmops Backend. Will commence after 800 seconds."), false);
             * }*/

            BotLog.Write(0, "MainCycle", "...done");

            /*
             * while (!MailTransmitter.CanExit)
             * {
             *  System.Threading.Thread.Sleep(50);
             * }*/

            _socketServer.Stop();

            Thread.Sleep(2000);
        }
Ejemplo n.º 57
0
        public void run()
        {
            AppDomain.CurrentDomain.UnhandledException          += new System.UnhandledExceptionEventHandler(Server.App_ThreadException);
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;


            FleckLog.Level = LogLevel.Error;
            allSockets     = new List <WebClient>();
            var server = new WebSocketServer("ws://localhost:43332/webtrader"); //use port 80 later + load config file

            try
            {
                server.Start(socket =>
                {
                    socket.OnOpen = () =>
                    {
                        try
                        {
                            Console.WriteLine(string.Format("Open: {0}:{1}", socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort));
                            lock (allSocketsLock)
                            {
                                allSockets.Add(new WebClient(socket, this));
                            }
                        }
                        catch { }
                    };
                    socket.OnClose = () =>
                    {
                        try
                        {
                            Console.WriteLine(string.Format("Close: {0}:{1}", socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort));
                            lock (allSocketsLock)
                            {
                                var sock = allSockets.Where(xe => xe != null && xe.iweb == socket).FirstOrDefault();

                                allSockets.Remove(sock);

                                sock.player.loggedIn = false;
                                sock.player.apistate = 0;
                            }
                        }
                        catch { }
                    };
                    socket.OnMessage = message =>
                    {
                        Console.WriteLine(message);
                        // allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                    };
                    socket.OnBinary = message =>
                    {
                        try
                        {
                            var sock = allSockets.Where(xe => xe != null && xe.iweb == socket).FirstOrDefault();
                            sock.ProcessMessage(message);
                        }
                        catch
                        {
                        }
                        // allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                    };
                });
            }
            catch
            {
            }

            KeepAliveThread = new System.Threading.Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        WebClient[] socks = new WebClient[allSockets.Count];

                        lock (allSocketsLock)
                        {
                            allSockets.CopyTo(socks);
                        }
                        foreach (var socket in socks)
                        {
                            if (socket.player == null)
                            {
                                continue;
                            }

                            if ((socket.player.apistate == 1 &&
                                 (socket.player.keepalive + 15000) < Server.tickcount.ElapsedMilliseconds))
                            {
                                Console.WriteLine(string.Format("Close: {0}:{1}", socket.iweb.ConnectionInfo.ClientIpAddress, socket.iweb.ConnectionInfo.ClientPort));
                                lock (allSocketsLock)
                                {
                                    allSockets.Remove(socket);
                                }
                                socket.player.loggedIn = false;
                                socket.player.apistate = 0;
                            }

                            System.Threading.Thread.Sleep(100);
                        }
                    }
                    catch { }
                }
            });
            KeepAliveThread.Start();

            Console.WriteLine(string.Format("ControlPanelListener is listening on {0}:{1}...", "0.0.0.0", "8181"), ConsoleColor.Green);
        }
 public void StopServer()
 {
     WebSocketServer.Stop();
 }
Ejemplo n.º 59
0
        private void Start()
        {
            if (useCustomContentServer)
            {
                RendereableAssetLoadHelper.useCustomContentServerUrl = true;
                RendereableAssetLoadHelper.customContentServerUrl    = customContentServerUrl;
            }

#if UNITY_EDITOR
            DCL.DataStore.i.debugConfig.isWssDebugMode = true;

            ws = new WebSocketServer("ws://localhost:5000");
            ws.AddWebSocketService <DCLWebSocketService>("/dcl");
            ws.Start();

            if (openBrowserWhenStart)
            {
                string baseUrl     = "";
                string debugString = "";

                if (baseUrlMode == BaseUrl.CUSTOM)
                {
                    baseUrl = baseUrlCustom;
                }
                else
                {
                    baseUrl = "http://localhost:3000/?";
                }

                switch (environment)
                {
                case Environment.USE_DEFAULT_FROM_URL:
                    break;

                case Environment.LOCAL:
                    debugString = "DEBUG_MODE&";
                    break;

                case Environment.ZONE:
                    debugString = "ENV=zone&";
                    break;

                case Environment.TODAY:
                    debugString = "ENV=today&";
                    break;

                case Environment.ORG:
                    debugString = "ENV=org&";
                    break;
                }

                if (forceLocalComms)
                {
                    debugString += "LOCAL_COMMS&";
                }

                if (allWearables)
                {
                    debugString += "ALL_WEARABLES&";
                }

                if (testWearables)
                {
                    debugString += "TEST_WEARABLES&";
                }

                if (enableTutorial)
                {
                    debugString += "RESET_TUTORIAL&";
                }

                if (soloScene)
                {
                    debugString += "LOS=0&";
                }

                if (builderInWorld)
                {
                    debugString += "ENABLE_BUILDER_IN_WORLD&";
                }

                if (questsEnabled)
                {
                    debugString += "QUESTS_ENABLED&";
                }

                string debugPanelString = "";

                if (debugPanelMode == DebugPanel.Engine)
                {
                    debugPanelString = ENGINE_DEBUG_PANEL + "&";
                }
                else if (debugPanelMode == DebugPanel.Scene)
                {
                    debugPanelString = SCENE_DEBUG_PANEL + "&";
                }

                Application.OpenURL(
                    $"{baseUrl}{debugString}{debugPanelString}position={startInCoords.x}%2C{startInCoords.y}&ws=ws%3A%2F%2Flocalhost%3A5000%2Fdcl");
            }
#endif
        }
Ejemplo n.º 60
-1
        static void Main(string[] args)
        {
            var webSocketServer = new WebSocketServer("ws://localhost:8081");
            var sockets = new List<IWebSocketConnection>();

            webSocketServer.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    sockets.Add(socket);
                };

                socket.OnMessage = mensagem =>
                {
                    foreach (var s in sockets)
                    {
                        s.Send(mensagem);
                    }
                };

                socket.OnClose = () =>
                {
                    sockets.Remove(socket);
                };
            });

            Console.ReadKey();
        }