static void Main(string[] args) { // test1 _Server = new WatsonWsServer("localhost", 9000, false); _Server.ClientConnected += (s, a) => { /* Console.WriteLine("Client " + a.IpPort + " connected"); */ }; _Server.ClientDisconnected += (s, a) => { /* Console.WriteLine("Client " + a.IpPort + " disconnected"); */ }; _Server.MessageReceived += (s, a) => { /* Console.WriteLine(Encoding.UTF8.GetString(a.Data)); */ }; _Server.Start(); Console.WriteLine("Test 1 with server started: " + ClientTask()); // test2 Task.Delay(1000).Wait(); _Server.Stop(); Console.WriteLine("Test 2 with server stopped: " + ClientTask()); // test3 Task.Delay(1000).Wait(); _Server.Start(); Console.WriteLine("Test 3 with server restarted: " + ClientTask()); // test4 Task.Delay(1000).Wait(); _Server.Dispose(); Console.WriteLine("Test 4 with server disposed: " + ClientTask()); // test5 Task.Delay(1000).Wait(); _Server = new WatsonWsServer("localhost", 9000, false); _Server.ClientConnected += (s, a) => { /* Console.WriteLine("Client " + a.IpPort + " connected"); */ }; _Server.ClientDisconnected += (s, a) => { /* Console.WriteLine("Client " + a.IpPort + " disconnected"); */ }; _Server.MessageReceived += (s, a) => { /* Console.WriteLine(Encoding.UTF8.GetString(a.Data)); */ }; _Server.Start(); Console.WriteLine("Test 5 with server started: " + ClientTask()); }
public ServerWatsonWs() { _server.ClientConnected += ClientConnected; _server.ClientDisconnected += ClientDisconnected; _server.MessageReceived += MessageReceived; _server.Start(); }
public BasicControlMessageConsumer(WatsonWsServer socket) { this.socket = socket; socket.ClientConnected += ClientConnected; socket.ClientDisconnected += ClientDisconnected; socket.Start(); }
public AsynchronousWebSocketListener(string IP, int Port) { WatsonWsServer server = new WatsonWsServer(IP, Port, true | false); server.ClientConnected += ClientConnected; server.ClientDisconnected += ClientDisconnected; server.MessageReceived += MessageReceived; server.Start(); }
public WebsocketService() { Server = new WatsonWsServer("127.0.0.1", 5003, false); Clients = new List <string>(); Server.ClientConnected += Server_ClientConnected; Server.ClientDisconnected += Server_ClientDisconnected; Server.MessageReceived += Server_MessageReceived; Console.WriteLine("starting server"); Server.Start(); }
static void InitializeServer() { server = new WatsonWsServer( serverIp, serverPort, ssl); server.ClientConnected += ClientConnected; server.ClientDisconnected += ClientDisconnected; server.MessageReceived += MessageReceived; server.Logger = Logger; server.Start(); }
public void Start() { Instance = this; manager = new ServerManager(); server = new WatsonWsServer("", 3005, false); server.ClientConnected += ClientConnected; server.ClientDisconnected += ClientDisconnected; server.MessageReceived += MessageReceived; server.Start(); Console.WriteLine("Server started."); }
public async Task MainAsync() { responder = new WebsocketResponder(this); Path = setStorage ?? Environment.GetEnvironmentVariable("ANDROID_STORAGE", EnvironmentVariableTarget.Machine); if (Path == null) { Path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/android_bot/"; Console.WriteLine("%ANDROID_STORAGE% has not been set, falling back to " + Path); } if (!Path.EndsWith("/")) { Console.WriteLine("%ANDROID_STORAGE% does not end with a backslash"); Path += "/"; } ApiKey = ApiKey ?? Environment.GetEnvironmentVariable("ANDROID_STEAM_API", EnvironmentVariableTarget.Machine); Client.Log += Log; Client.MessageReceived += (arg) => MessageReceived(arg, false); Client.MessageUpdated += MessageUpdated; await Client.LoginAsync(TokenType.Bot, DiscordToken); await Client.StartAsync(); MuteSystem = new MuteSystem(this); await MuteSystem.Initialise(); Listeners.AddRange(ActiveListeners); foreach (MessageListener listener in Listeners) { await listener.Initialise(this); Console.WriteLine(listener.GetType().Name + " initialised"); } WebsocketServer.Start(); await Task.Run(() => { while (true) { if (shouldShutDown && Client.ConnectionState == ConnectionState.Disconnected) { break; } } }); }
public void Start() { if (IsActive) { Stop(); } _socket = new WatsonWsServer(IP, Port, false); _socket.MessageReceived += Socket_MessageReceived; _socket.Start(); _timer.Interval = KeepAliveInterval.TotalMilliseconds; _timer.Start(); }
public void Start() { try { _server = new WatsonWsServer(ServerUrl.DnsSafeHost, ServerUrl.Port, false); _server.MessageReceived += Server_MessageReceived; _server.Start(); _timer.Start(); IsOpen = true; } catch (Exception ex) { Error?.Invoke(this, ex); } }
public bool OpenConnection() { try { WatsonWsServer server = new WatsonWsServer("127.0.0.1", 3000, false); server.ClientConnected += ClientConnected; server.ClientDisconnected += ClientDisconnected; server.MessageReceived += MessageReceived; server.Logger = Logger; server.Start(); return(true); } catch (Exception e) { Console.WriteLine(e); return(false); } }
public static void Run(Arguments args) { // Save the configuration for later Args = args; // Configure the Serilog Logging Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .CreateLogger(); // Print the a message with information about the current system if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Log.Information($"Starting LambentLight Daemon in Windows"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Log.Information($"Starting LambentLight Daemon in Linux"); } // If we are on something not supported, return else { Log.Fatal("Unsuported operating system detected!"); Log.Fatal("LambentLight can only be used on Windows and Linux"); Environment.Exit(1); } // And run the websocket server WatsonWsServer server = new WatsonWsServer(args.IP, args.Port, args.SSL) { PermittedIpAddresses = args.Allowed.ToList() }; server.MessageReceived += Server_MessageReceived; server.ClientConnected += Server_ClientConnected; server.ClientDisconnected += Server_ClientDisconnected; server.ServerStopped += Server_ServerStopped; Log.Information("Starting LambentLight in Daemon Mode on {0}:{1}", args.IP, args.Port); server.Start(); Thread.Sleep(Timeout.Infinite); }
static void Main(string[] args) { using (WatsonWsServer wss = new WatsonWsServer(_Hostname, _Port, false)) { wss.ClientConnected += (s, e) => Console.WriteLine("Client connected: " + e.IpPort); wss.ClientDisconnected += (s, e) => Console.WriteLine("Client disconnected: " + e.IpPort); wss.MessageReceived += (s, e) => { Console.WriteLine("Server message received from " + e.IpPort + ": " + Encoding.UTF8.GetString(e.Data)); _ClientIpPort = e.IpPort; }; wss.Start(); Thread.Sleep(2500); using (WatsonWsClient wsc = new WatsonWsClient(_Hostname, _Port, false)) { wsc.ServerConnected += (s, e) => Console.WriteLine("Client connected to server"); wsc.ServerDisconnected += (s, e) => Console.WriteLine("Client disconnected from server"); wsc.MessageReceived += (s, e) => Console.WriteLine("Client received message from server: " + Encoding.UTF8.GetString(e.Data)); wsc.Start(); Thread.Sleep(2500); Console.WriteLine("Sending message from client to server..."); wsc.SendAsync("Hello from client").Wait(); Thread.Sleep(2500); Console.WriteLine("Sending message from server to client..."); wss.SendAsync(_ClientIpPort, "Hello from server").Wait(); Console.WriteLine("Press ENTER to exit"); Console.ReadLine(); } } }
static void Main(string[] args) { msgData = Encoding.UTF8.GetBytes(RandomString(msgLength)); sendDelay = numClients * 20; using (server = new WatsonWsServer(hostname, port, false)) { #region Start-Server serverStats = new Statistics(); server.ClientConnected += (s, e) => { Console.WriteLine("Client connected: " + e.IpPort); lock (clientsLock) { clients.Add(e.IpPort); } }; server.ClientDisconnected += (s, e) => { Console.WriteLine("*** Client disconnected: " + e.IpPort); lock (clientsLock) { if (clients.Contains(e.IpPort)) { clients.Remove(e.IpPort); } } }; server.MessageReceived += (s, e) => { serverStats.AddRecv(e.Data.Length); }; // server.Logger = Logger; server.Start(); #endregion #region Start-and-Wait-for-Clients for (int i = 0; i < numClients; i++) { Console.WriteLine("Starting client " + (i + 1) + "..."); Task.Run(() => ClientTask()); Task.Delay(250).Wait(); } while (true) { Task.Delay(1000).Wait(); int connected = 0; lock (clientsLock) { connected = clients.Count; } if (connected == numClients) { break; } Console.WriteLine(connected + " of " + numClients + " connected, waiting"); } Console.WriteLine("All clients connected!"); serverReady = true; #endregion #region Send-Messages-to-Clients for (int i = 0; i < messagesPerClient; i++) { for (int j = 0; j < numClients; j++) { server.SendAsync(clients[j], msgData).Wait(); serverStats.AddSent(msgData.Length); } } #endregion #region Wait-for-Clients while (true) { Task.Delay(5000).Wait(); int remaining = 0; lock (clientsLock) { remaining = clients.Count; if (remaining < 1) { break; } Console.WriteLine(DateTime.Now.ToUniversalTime().ToString("HH:mm:ss.ffffff") + " waiting for " + remaining + " clients: "); foreach (string curr in clients) { Console.WriteLine("| " + curr); } } } #endregion #region Statistics Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Server statistics:"); Console.WriteLine(" " + serverStats.ToString()); Console.WriteLine(""); Console.WriteLine("Client statistics"); foreach (Statistics stats in clientStats) { Console.WriteLine(" " + stats.ToString()); } Console.WriteLine(""); #endregion } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var stopRequested = false; #if !SKIP_WS // SetUp Server for GoXLR: _server.ClientConnected += async(sender, args) => { //When GoXLR is connected, ask for Profiles. Logger.Error("Client connected: " + args.IpPort); _logger.LogInformation("Client connected: " + args.IpPort); try { //var model = GetProfilesRequest.Create(); //var json = System.Text.Json.JsonSerializer.Serialize(model); //_logger.LogInformation(json); //await _server.SendAsync(args.IpPort, json, stoppingToken); } catch (Exception e) { Logger.Error($"{e}"); _logger.LogError(e.ToString()); } }; _server.ClientDisconnected += (sender, args) => { Logger.Error("Client disconnected: " + args.IpPort); }; _server.MessageReceived += (sender, args) => { try { var json = Encoding.UTF8.GetString(args.Data); Logger.Error("Message received from " + args.IpPort + ": " + json); _logger.LogInformation("Message received from " + args.IpPort); //var response = JsonSerializer.Deserialize<GetProfilesResponse>(json); _messageProcessor.UpdateChoice(new ChoiceUpdate { Id = PluginActionType.DiscordSelfMute.ToString().ToSnakeCase(), //Value = response?.Payload.Profiles ?? new[] { "No profiles!" } Value = new[] { "No profiles!" } }); } catch (Exception e) { Logger.Error($"{e}"); _logger.LogError(e.ToString()); } }; _server.Start(); #endif //Setup Client for TouchPortal: // On Plugin Connect Event _messageProcessor.OnConnectEventHandler += () => { Logger.Error($"Plugin Connected to TouchPortal"); }; // On Action Event _messageProcessor.OnActionEvent += async(actionId, dataList) => { Logger.Error($"Action Event Fired: {actionId}"); #if !SKIP_WS try { var clients = _server.ListClients(); var client = clients.SingleOrDefault(); if (client != null) { Logger.Error($"Discord.Plugin Client found: {client}"); Enum.TryParse(typeof(PluginActionType), actionId, out object?output); PluginActionType?actionType = output as PluginActionType?; switch (actionType) { case PluginActionType.DiscordSelfMute: case PluginActionType.DiscordSelfDeafen: { var profile = dataList.Single().Value; //await _server.SendAsync(client, json, stoppingToken); break; } } } else { Logger.Error("No Discord Clients connected. Restart the Discord App"); } } catch (Exception e) { Logger.Error($"{e}"); } #endif foreach (var actionData in dataList) { Logger.Error($"Id: {actionData.Id} Value: {actionData.Value}"); } }; // On List Change Event _messageProcessor.OnListChangeEventHandler += (actionId, value) => { Logger.Error($"Choice Event Fired."); }; // On Plugin Disconnect _messageProcessor.OnCloseEventHandler += () => { Console.Write($"Plugin Quit Command"); stopRequested = true; }; // Send State Update _messageProcessor.UpdateState(new StateUpdate { Id = "SomeStateId", Value = "New Value" }); // Send Choice Update _messageProcessor.UpdateChoice(new ChoiceUpdate { Id = PluginActionType.DiscordSelfMute.ToString().ToSnakeCase(), Value = new[] { "No Value" } }); // Run Listen and pairing _ = Task.WhenAll(new Task[] { _messageProcessor.Listen(), _messageProcessor.TryPairAsync() }); try { // Do whatever you want in here while (!stoppingToken.IsCancellationRequested && !stopRequested) { //_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } finally { _hostApplicationLifetime.StopApplication(); } }
static void Main(string[] args) { _ServerIp = InputString("Server IP:", "localhost", true); _ServerPort = InputInteger("Server port:", 9000, true, true); _Ssl = InputBoolean("Use SSL:", false); InitializeServer(); bool runForever = true; while (runForever) { Console.Write("Command [? for help]: "); string userInput = Console.ReadLine()?.Trim(); if (string.IsNullOrEmpty(userInput)) { continue; } string[] splitInput = userInput.Split(new string[] { " " }, 2, StringSplitOptions.None); string ipPort = null; bool success = false; switch (splitInput[0]) { case "?": Console.WriteLine("Available commands:"); Console.WriteLine(" ? help (this menu)"); Console.WriteLine(" q quit"); Console.WriteLine(" cls clear screen"); Console.WriteLine(" dispose dispose of the server"); Console.WriteLine(" reinit reinitialize the server"); Console.WriteLine(" start start accepting new connections (listening: " + _Server.IsListening + ")"); Console.WriteLine(" stop stop accepting new connections"); Console.WriteLine(" list list clients"); Console.WriteLine(" stats display server statistics"); Console.WriteLine(" send ip:port text message send text to client"); Console.WriteLine(" send ip:port bytes message send binary data to client"); Console.WriteLine(" kill ip:port disconnect a client"); break; case "q": runForever = false; break; case "cls": Console.Clear(); break; case "dispose": _Server.Dispose(); break; case "reinit": InitializeServer(); break; case "start": _Server.Start(); break; case "stop": _Server.Stop(); break; case "list": var clients = new List <string>(_Server.ListClients()); if (clients.Count > 0) { Console.WriteLine("Clients"); foreach (string curr in clients) { Console.WriteLine(" " + curr); } } else { Console.WriteLine("[No clients connected]"); } break; case "stats": Console.WriteLine(_Server.Stats.ToString()); break; case "send": if (splitInput.Length != 2) { break; } splitInput = splitInput[1].Split(new string[] { " " }, 3, StringSplitOptions.None); if (splitInput.Length != 3) { break; } if (splitInput[0].Equals("last")) { ipPort = _LastIpPort; } else { ipPort = splitInput[0]; } if (String.IsNullOrEmpty(splitInput[2])) { break; } if (splitInput[1].Equals("text")) { success = _Server.SendAsync(ipPort, splitInput[2]).Result; } else if (splitInput[1].Equals("bytes")) { byte[] data = Encoding.UTF8.GetBytes(splitInput[2]); success = _Server.SendAsync(ipPort, data).Result; } else { break; } if (!success) { Console.WriteLine("Failed"); } else { Console.WriteLine("Success"); } break; case "kill": if (splitInput.Length != 2) { break; } _Server.DisconnectClient(splitInput[1]); break; default: Console.WriteLine("Unknown command: " + userInput); break; } } }
static void Main(string[] args) { string header = "[Server] "; using (server = new WatsonWsServer(hostname, port, false)) { #region Start-Server server.ClientConnected += (s, e) => { clientIpPort = e.IpPort; Console.WriteLine(header + "client connected: " + e.IpPort); }; server.ClientDisconnected += (s, e) => { clientIpPort = null; Console.WriteLine(header + "client disconnected: " + e.IpPort); }; server.MessageReceived += async(s, e) => { // echo it back serverStats.AddRecv(e.Data.Count); await server.SendAsync(e.IpPort, e.Data); serverStats.AddSent(e.Data.Count); }; server.Logger = Logger; server.Start(); Console.WriteLine(header + "started"); #endregion #region Start-Client-and-Send-Messages Task.Run(() => ClientTask()); Task.Delay(1000).Wait(); while (String.IsNullOrEmpty(clientIpPort)) { Task.Delay(1000).Wait(); Console.WriteLine(header + "waiting for client connection"); } ; Console.WriteLine(header + "detected client " + clientIpPort + ", sending messages"); for (int i = 0; i < serverSendMessageCount; i++) { byte[] msgData = Encoding.UTF8.GetBytes(RandomString(serverMessageLength)); server.SendAsync(clientIpPort, msgData).Wait(); serverStats.AddSent(msgData.Length); } Console.WriteLine(header + "messages sent"); #endregion #region Wait-for-and-Echo-Client-Messages while (!String.IsNullOrEmpty(clientIpPort)) { Console.WriteLine(header + "waiting for client to finish"); Task.Delay(1000).Wait(); } #endregion #region Statistics Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Server statistics:"); Console.WriteLine(" " + serverStats.ToString()); Console.WriteLine(""); Console.WriteLine("Client statistics"); Console.WriteLine(" " + clientStats.ToString()); Console.WriteLine(""); #endregion Console.WriteLine("Press ENTER to exit"); Console.ReadLine(); } }
static void Main(string[] args) { int exitCode = 0; log.Start(); try { CheckConfig(); log.Add($"Starting server ({ typeof(Program).Assembly.GetName().Version})"); serverConfig.Load(); clients = new Dictionary <User, bool>(); InitializeModules(); InitializeServer(); cleaner.Start(); server.Start(); while (ShowAndHandleMenu(Console.ReadLine())) { } } catch (Exception ex) { exitCode = 1; log.Add(ex.ToString(), MessageType.Error); } finally { log.Add("Closing server"); log.Add("Receiving stopped"); stopReceive = true; if (!(server is null)) { log.Add("Waiting for requests to be processed"); while (clients.Any(x => x.Value)) { Thread.Sleep(10); } log.Add("Disconnecting users"); foreach (KeyValuePair <User, bool> user in clients) { server.DisconnectClient(user.Key.IpPort); } server.Dispose(); } cleaner.Stop(); log.Stop(); GC.Collect(); Environment.Exit(exitCode); } }