public void SetUp() { _server = new WebSocketServer(54321, IPAddress.Loopback) {OnReceive = OnServerReceive}; _server.Start(); _client = new WebSocketClient("ws://127.0.0.1:54321/path") { Origin = "localhost", OnReceive = OnClientReceive }; _client.Connect(); }
public static void Start() { Server = new WebSocketServer(81, IPAddress.Any); Server.OnConnect = OnConnected; Server.Start(); Utilities.Logger.Infos("Websocket server started !"); }
internal static bool Init(int bindPort, int maxConnections) { _Port = bindPort; _maxConnections = maxConnections; _activeConnections = new HashSet<int>(); try { var aServer = new WebSocketServer(_Port, IPAddress.Any) { OnReceive = OnReceive, OnSend = OnSend, OnConnected = OnConnect, OnDisconnect = OnDisconnect, TimeOut = new TimeSpan(0, 5, 0) }; aServer.Start(); Console.WriteLine(" WebSockets initialized, listining on port: " + _Port + "."); return true; } catch { Console.WriteLine(" failed to initialize WebSockets!"); return false; } }
/// <summary> /// Starts the specified port number. /// </summary> /// <param name="portNumber">The port number.</param> public void Start(int portNumber) { try { WebSocketServer = new WebSocketServer(portNumber, IPAddress.Any) { OnConnected = OnAlchemyWebSocketClientConnected, TimeOut = TimeSpan.FromHours(24) }; WebSocketServer.Start(); _hasStarted = true; } catch (SocketException ex) { _logger.ErrorException("The web socket server is unable to start on port {0} due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system.", ex, portNumber); throw; } Port = portNumber; _logger.Info("Alchemy Web Socket Server started"); }
public void ClientShouldNotConnectWithInvalidProtocol() { _server = new WebSocketServer(54321, IPAddress.Loopback); _server.Start(); _client = new WebSocketClient("ws://127.0.0.1:54321/path") {Origin = "localhost", SubProtocols = new[] {"test", "test2"}}; _client.Connect(); }
public MasterServer() { sessions = new List<ClientSession>(); server = new WebSocketServer(9998,IPAddress.Any); server.OnConnected = OnConnected; server.OnReceive = OnReceive; server.Start(); }
/// <summary> /// Initializes the WebSocket server and begins accepting connections. /// </summary> public static void Intitialize() { wsserver = new WebSocketServer(Config.ServerPort, IPAddress.Any); wsserver.OnConnect = OnConnect; wsserver.OnConnected = OnConnected; wsserver.OnDisconnect = OnDisconnect; wsserver.OnReceive = OnReceive; wsserver.OnSend = OnSend; wsserver.Start(); }
public void ClientShoulConnectWithValidProtocol() { _server = new WebSocketServer(54321, IPAddress.Loopback) { SubProtocols = new[] { "test" }}; _server.Start(); _client = new WebSocketClient("ws://127.0.0.1:54321/path") { Origin = "localhost", SubProtocols = new[] { "test", "test2" } }; _client.Connect(); Assert.IsTrue(_client.IsAuthenticated); Assert.AreEqual("test", _client.CurrentProtocol); }
public Websocket() { ws = new WebSocketServer(9000, System.Net.IPAddress.Any) { OnReceive = ReceivedMsg, OnConnected = newConnection, OnConnect = attemptingConnect, OnDisconnect = DisconnectedConnection }; ws.Start(); }
private static void Main(string[] args) { var aServer = new WebSocketServer(81, IPAddress.Any) { OnReceive = OnReceive, TimeOut = new TimeSpan(0, 5, 0) }; aServer.Start(); if (!SpotifyAPI.IsSpotifyRunning()) { spotifyClient.RunSpotify(); Thread.Sleep(5000); } if (!SpotifyAPI.IsSpotifyWebHelperRunning()) { spotifyClient.RunSpotifyWebHelper(); Thread.Sleep(4000); } if (!spotifyClient.Connect()) { Console.WriteLine("SpotifyAPI couldn't load!"); } var mh = spotifyClient.GetMusicHandler(); var eh = spotifyClient.GetEventHandler(); spotifyClient.Update(); Song = mh.GetCurrentTrack().GetTrackName(); Artist = mh.GetCurrentTrack().GetArtistName(); Album = mh.GetCurrentTrack().GetAlbumName(); AlbumURL = mh.GetCurrentTrack().GetAlbumArtURL(AlbumArtSize.SIZE_320); Volume = "100%"; Time = formatTime(0) + "/" + formatTime(mh.GetCurrentTrack().GetLength()); Length = mh.GetCurrentTrack().GetLength(); eh.OnTrackChange += TrackChange; eh.OnVolumeChange += VolumeChange; eh.OnTrackTimeChange += TimeChange; eh.ListenForEvents(true); while (true) { Thread.Sleep(1000); } }
public void Start() { InitializeSavedJukeboxes(); // Small race condition exists now; we may not set the OnReceive handler before data comes in socketServer = new WebSocketServer(Constants.WebSocketPort, IPAddress.Any); socketServer.OnConnect += OnConnect; socketServer.OnDisconnect += OnDisconnect; socketServer.Start(); ts.TraceEvent(TraceEventType.Information, 0, "Started"); }
public WebsocketGraph(TimeSpan timeout, int port, int? historySendOnConnectCount) { m_aServer = new WebSocketServer(port, System.Net.IPAddress.Any) { OnReceive = OnReceive, OnSend = OnSend, OnConnected = OnConnect, OnDisconnect = OnDisconnect, TimeOut = timeout }; m_historySendOnConnectCount = historySendOnConnectCount; m_aServer.Start(); }
/// <summary> /// Starts the specified port number. /// </summary> /// <param name="portNumber">The port number.</param> public void Start(int portNumber) { WebSocketServer = new WebSocketServer(portNumber, IPAddress.Any) { OnConnected = OnAlchemyWebSocketClientConnected, TimeOut = TimeSpan.FromHours(12) }; WebSocketServer.Start(); Port = portNumber; _logger.Info("Alchemy Web Socket Server started"); }
static void Main(string[] arguments) { ActiveContexts = new List<UserContext>(); WebSocketServer server = new WebSocketServer(81, IPAddress.Any) { OnReceive = OnReceive, OnSend = OnSend, OnConnected = OnConnect, OnDisconnect = OnDisconnect, TimeOut = new TimeSpan(0, 0, 5) }; server.Start(); }
public void Start(WebSocketHandler handler) { _server = new WebSocketServer(81, IPAddress.Any) { OnReceive = new OnEventDelegate(handler.OnReceive), OnSend = new OnEventDelegate(handler.OnSend), OnConnect = new OnEventDelegate(handler.OnConnect), OnConnected = new OnEventDelegate(handler.OnConnected), OnDisconnect = new OnEventDelegate(handler.OnDisconnect), TimeOut = new TimeSpan(0, 5, 0) }; Console.WriteLine("Starting Server"); _server.Start(); }
public static void run() { //subscribe to the right event InterceptKeys.OnKeyPressedEvent += new onKeyPressed(listenKeyPressed); InterceptKeys.OnKeyReleasedEvent += new onKeyReleased(listenKeyReleased); MouseHook.OnMousePressedEvent += new onMousePressed(listenMousePressed); MouseHook.OnMouseReleasedEvent += new onMouseReleased(listenMouseReleased); //We're running the server locally aServer = new WebSocketServer(3939, IPAddress.Parse("127.0.0.1")) { OnConnected = OnConnected, OnDisconnect = OnDisconnect, TimeOut = new TimeSpan(0, 5, 0) }; aServer.Start(); }
public TossServer() { aServer = new WebSocketServer(false, 81, IPAddress.Any) { OnReceive = OnReceive, OnSend = OnSend, OnConnect = OnConnect, OnDisconnect = OnDisconnect, TimeOut = new TimeSpan(0, 5, 0) }; aServer.Start(); pmsSrv = new PMSServer(); pmsSrv.ReqPMSSetEvent += pmsSrv_ReqPMSSetEvent; cdrSrv = new CDRecorder(); cdrSrv.RequestCDREvent += cdrSrv_RequestCDREvent; }
public WebSocket(int port, string chromeExtensionOrigin) { this.Port = port; this.ChromeExtensionOrigin = chromeExtensionOrigin; _clients = new List<UserContext>(); var chromeExt = ""; if (!string.IsNullOrEmpty(ChromeExtensionOrigin)) chromeExt = "chrome-extension://" + ChromeExtensionOrigin; _server = new WebSocketServer(this.Port, IPAddress.Loopback) { OnReceive = OnReceive, OnConnected = OnConnect, OnDisconnect = OnDisconnect, TimeOut = new TimeSpan(0, 5, 0), Origin = chromeExt }; _server.Start(); }
/// <summary> /// Starts the specified port number. /// </summary> /// <param name="portNumber">The port number.</param> public void Start(int portNumber) { _logger.Info("Starting Alchemy web socket server on port {0}", portNumber); try { WebSocketServer = new WebSocketServer(portNumber, IPAddress.Any) { OnConnected = OnAlchemyWebSocketClientConnected, TimeOut = TimeSpan.FromHours(24) }; #if __MonoCS__ //Linux: port below 1024 require root or cap_net_bind_service if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) { if (Syscall.getuid() == 0) { WebSocketServer.FlashAccessPolicyEnabled = true; } else { WebSocketServer.FlashAccessPolicyEnabled = false; } } #endif WebSocketServer.Start(); } catch (Exception ex) { _logger.ErrorException("The web socket server is unable to start on port {0} due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system.", ex, portNumber); throw; } Port = portNumber; _logger.Info("Alchemy Web Socket Server started"); }
void Start() { // search for textures var texturepath = String.Concat(Environment.CurrentDirectory, @"\webroot\textures"); var info = new DirectoryInfo(texturepath); var fileInfo = info.GetFiles(); var availableTextures = new String[fileInfo.Length]; foreach(FileInfo file in fileInfo){ Debug.Log(file.Name); } // write config file string path = String.Concat(Environment.CurrentDirectory, @"\webroot\js\server-config.js"); TextWriter configFile = new StreamWriter(path); configFile.WriteLine("function ServerConfig(){"); configFile.WriteLine(String.Concat(@"this.ip = """, Network.player.ipAddress, @""";")); configFile.WriteLine(String.Concat(@"this.screenWidth = ", Screen.width, @";")); configFile.WriteLine(String.Concat(@"this.screenHeight = ", Screen.height, @";")); // write texture array configFile.WriteLine("this.textures = ["); for(var i = 0; i < fileInfo.Length; i++){ if(i == fileInfo.Length - 1) { configFile.WriteLine(String.Concat(@"""", fileInfo[i].Name, @"""")); } else { configFile.WriteLine(String.Concat(@"""", fileInfo[i].Name, @""",")); } } configFile.WriteLine("]"); configFile.WriteLine("}"); configFile.Close (); try { // create and start the host appHost = new AppHost(); appHost.Config.WebHostPhysicalPath = Path.Combine(Directory.GetCurrentDirectory(), webrootPath); appHost.Init(); appHost.Start(host); Debug.Log("Server listening at http://" + Network.player.ipAddress + "/home"); Cache = appHost.GetCacheClient(); } catch (Exception exeption) { Debug.Log(exeption); Cache = new MemoryCacheClient(); } var instance = FindObjectOfType(typeof(Exec)) as Exec; if (instance == null) { instance = gameObject.AddComponent<Exec>(); } wsServer = new WebSocketServer(1081) { OnDisconnect = context => { print("DISCONNECT"); }, // Called when the server connects OnConnected = context => { var response = (object)null; isConnected = true; GameObject cached = default(GameObject); shouldHideIP = true; OnGUI(); if (!OnlineUsers.ContainsKey(context.ClientAddress.ToString())) { OnlineUsers[context.ClientAddress.ToString()] = context; } // Called when the server disconnects context.SetOnDisconnect((e) => { UserContext ctx = null; OnlineUsers.TryRemove(e.ClientAddress.ToString(), out ctx); if (ctx != null) { Exec.OnMain(() => Debug.Log("User: "******" has disconnected")); } }); // Called when new data is received over the socket context.SetOnReceive((e) => { try { var jsonObject = JSON.Parse(e.DataFrame.ToString()); var eventIdentifier = jsonObject["event_identifier"].Value; var uuid = jsonObject["uuid"].Value; switch (eventIdentifier) { case "create_rect": Exec.OnMain(() => { GameObject rect = GameObject.CreatePrimitive(PrimitiveType.Quad); rect.name = uuid; rect.transform.position = new Vector3(0, 0, zIndexCounter); zIndexCounter--; //set shaders and custom behaviours rect.renderer.material.shader = Shader.Find("Custom/transform"); moveRect moveBehaviour = rect.AddComponent("moveRect") as moveRect; projectionMatrix matrix = rect.AddComponent("projectionMatrix") as projectionMatrix; vertexPositions vertexPositioning = rect.AddComponent<vertexPositions> () as vertexPositions; //set intitial position vertexPositioning.moveVertices(jsonObject["positions"]); //set the texture of the new rect var initTextureURL = jsonObject["texture"]["url"].Value; WWW initialtexture = new WWW(initTextureURL); while(!initialtexture.isDone) { var dumm = "blöd"; } Texture texture = initialtexture.texture; rect.renderer.material.mainTexture = texture; Debug.Log("Received create_rect command, new rect with uuid: " + uuid); }); break; case "delete_rect": Exec.OnMain(() => { GameObject rect = GameObject.Find(uuid); Destroy(rect); Debug.Log("Received delete_rect command for rect with uuid: " + uuid); }); break; case "move_rect": Exec.OnMain(() => { GameObject rect = GameObject.Find(uuid); var moveBehaviour = rect.GetComponent<vertexPositions>(); moveBehaviour.moveVertices(jsonObject["positions"]); Debug.Log("Received move_rect command"); }); break; case "move_vertice": // The index of the vertice that should be moved. var verticeIndex = 0; Vector2 verticeDelta; switch (jsonObject["vertice"].Value) { case ("top_left"): break; case ("top_right"): verticeIndex = 1; break; case ("bottom_right"): verticeIndex = 2; break; case ("bottom_left"): verticeIndex = 3; break; } var delta = jsonObject["vertice"]; verticeDelta.x = delta["x"].AsFloat; verticeDelta.y = delta["y"].AsFloat; Exec.OnMain(() => { GameObject rect = GameObject.FindWithTag(uuid); Debug.Log("Received move_vertice command for the vertice: " + jsonObject["vertice"].Value + " and delta: " + verticeDelta); }); break; case "change_texture": var textureURL = jsonObject["texture"]["url"].Value; Exec.OnMain(() => { WWW webTexture = new WWW(textureURL); //yield return webTexture; while(!webTexture.isDone) { var dumm = "blöd"; } Texture newTexture = webTexture.texture; GameObject rect = GameObject.Find(uuid); rect.renderer.material.mainTexture = newTexture; Debug.Log("Received change_texture command"); }); break; default: break; } var v = e.DataFrame.ToString().FromJson<Do>(); var ou = new { rcvd = e, t = DateTime.Now }; foreach (var userContext in OnlineUsers) { if (userContext.Key != context.ClientAddress.ToString()) { userContext.Value.Send(v.ToJson()); } } } catch (Exception exeption) { Exec.OnMain(() => Debug.Log(exeption)); } }); } }; // Starting the server wsServer.Start(); // suppossed to register the log callback... Application.RegisterLogCallback((log, stack, type) => { foreach (var userContext in OnlineUsers) { userContext.Value.Send(new { log, stack, type}.ToJson()); } }); }
/// <summary> /// Initialize the application and start the Alchemy Websockets server /// </summary> /// <param name="args"></param> static void Main(string[] args) { // Initialize the server on port 81, accept any IPs, and bind events. var aServer = new WebSocketServer(81, IPAddress.Any) { OnReceive = OnReceive, OnSend = OnSend, OnConnected = OnConnect, OnDisconnect = OnDisconnect, TimeOut = new TimeSpan(0, 5, 0) }; aServer.Start(); // Accept commands on the console and keep it alive var command = string.Empty; while (command != "exit") { command = Console.ReadLine(); } aServer.Stop(); }
static void Main(string[] args) { string SslFileName = @"C:\Astros\AstrosSocket\astros.com.pfx"; string SslPassword = @"c0sm0s"; bool IsSecure = true; WebSocketServer wss = new WebSocketServer(11234, IPAddress.Any) { OnReceive = OnReceive, OnConnect = OnConnect, OnSend = OnSend, OnDisconnect = OnDisconnect, OnConnected = OnConnected, FlashAccessPolicyEnabled = true, IsSecure = IsSecure, SSLCertificate = new X509Certificate2(SslFileName, SslPassword) }; Console.Title = "WebSocket Server Test"; Console.WriteLine("Starting server..."); wss.Start(); Console.WriteLine(" ... Server started"); Console.WriteLine("Waiting for incomming connections..."); Console.WriteLine("[Press enter to end server]"); string str = string.Empty; //while (string.IsNullOrEmpty(str) == true) { str = Console.ReadLine(); } Console.WriteLine("Stopping server..."); wss.Stop(); Console.WriteLine(" ... Server stopped"); // Force the program to terminate Environment.Exit(0); }
static void Main(string[] args) { SocketServer = new WebSocketServer(ServerPort, System.Net.IPAddress.Any) { OnReceive = OnReceive, OnConnected = OnConnect, OnDisconnect = OnDisconnect, TimeOut = new TimeSpan(0, 5, 0) }; SocketServer.Start(); System.Threading.Timer t = new System.Threading.Timer(timerTick, null, 0, HeartBeat * 1000); Console.WriteLine("WebServer Successfuly Started !"); Console.Write(">"); string _text = string.Empty; while (_text.ToLower() != "!exit") { _text = Console.ReadLine().Trim(); ConsoleSend(_text); Console.Write(">"); } SocketServer.Stop(); SocketServer = null; Console.WriteLine("Press any key to continue..."); Console.ReadLine(); Environment.Exit(0); }
static void Main(string[] args) { onlineConnections = new ConcurrentDictionary<string, UserContext>(); stopwatch = new Stopwatch(); mode = Modes.Depth1Byte; //mode = Modes.RGB; var aServer = new WebSocketServer(8100, System.Net.IPAddress.Any) { OnReceive = OnReceive, OnSend = OnSend, OnConnected = OnConnect, OnDisconnect = OnDisconnect, TimeOut = new TimeSpan(0, 5, 0) }; aServer.Start(); Console.WriteLine("Running Alchemy WebSocket Server ..."); Console.WriteLine("[Type \"exit\" and hit enter to stop the server]"); initializeKinect(); // Accept commands on the console and keep it alive var command = string.Empty; while (command != "exit") { command = Console.ReadLine(); } // Stop Kinect. if (null != sensor) { sensor.Stop(); } aServer.Stop(); }
public void Initialize(int port, string password, int adminId, long ssid) { this.Stop(); // Clear the message handling queue _messageQueue.Clear(); this.OnMessageQueueUpdated(); // Find existing state var existing = LoadState(ssid); _state = existing ?? new SyncState(ssid); _password = password; _adminId = adminId; _subSessionId = ssid; // Start new server _server = new WebSocketServer(port, IPAddress.Any) { OnReceive = OnReceive, OnConnected = OnConnected, OnDisconnect = OnDisconnect, TimeOut = new TimeSpan(0, 5, 0) }; _server.Start(); this.Status = ServerStatus.Active; _localServerInfo = ServerInfo.Local(port, password); // Start message queue handling thread _messageThread = new Thread(HandleMessageQueue); _messageThread.IsBackground = false; _messageThread.Start(); // Start ping loop _pingThread = new Thread(PingLoop); _pingThread.IsBackground = true; _pingThread.Start(); // Start web-update thread _webThread = new Thread(WebUpdateLoop); _webThread.IsBackground = true; _webThread.Start(); }
// Constructor public MainForm( ) { InitializeComponent( ); Application.Idle += new EventHandler( Application_Idle ); aServer = new WebSocketServer(8100, System.Net.IPAddress.Any) { OnReceive = OnReceive, OnSend = OnSend, OnConnected = OnConnect, OnDisconnect = OnDisconnect, TimeOut = new TimeSpan(0, 5, 0) }; aServer.Start(); }