private void SendResponse(Response response)
 {
     try
     {
         foreach (var client in _server.ListClients())
         {
             string json = "";
             if (Settings.Default.AddJsonRootObject)
             {
                 var root = new
                 {
                     Response = response
                 };
                 json = root.ToJson();
             }
             else
             {
                 json = response.ToJson();
             }
             _server.SendAsync(client, json);
             ResponseSent?.Invoke(this, json);
         }
     }
     catch (Exception ex)
     {
         Error?.Invoke(this, ex);
     }
 }
Example #2
0
        private bool OnClientConnect(string ipPort, IDictionary <string, string> data)
        {
            Console.WriteLine(" A new client connected from " + ipPort + "...");

            if (Users.SocketUsers.Users.ContainsKey(ipPort))
            {
                Console.WriteLine(" Detected faulty user data! Resetting socket user for " + ipPort + "...");
                Users.SocketUsers.Users.Remove(ipPort);
            }

            Users.SocketUsers.Users.Add(ipPort, new Users.SocketUser(ipPort));

            foreach (string client in (new List <string>(Socket.ListClients())))
            {
                new Socket.Events.GetOnlineCountEvent(client);
            }

            return(true);
        }
Example #3
0
        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("  list                  list clients");
                    Console.WriteLine("  stats                 display server statistics");
                    Console.WriteLine("  send ip:port message  send message to client");
                    Console.WriteLine("  kill ip:port          disconnect a client");
                    break;

                case "q":
                    runForever = false;
                    break;

                case "cls":
                    Console.Clear();
                    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[] { " " }, 2, StringSplitOptions.None);
                    if (splitInput.Length != 2)
                    {
                        break;
                    }
                    ipPort = splitInput[0];
                    string data = splitInput[1];

                    if (string.IsNullOrEmpty(data))
                    {
                        break;
                    }
                    success = server.SendAsync(ipPort, data).Result;
                    break;

                case "kill":
                    if (splitInput.Length != 2)
                    {
                        break;
                    }
                    server.DisconnectClient(splitInput[1]);
                    break;

                default:
                    Console.WriteLine("Unknown command: " + userInput);
                    break;
                }
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            Console.Write("Server IP        : ");
            serverIp = Console.ReadLine();

            Console.Write("Server Port      : ");
            serverPort = Convert.ToInt32(Console.ReadLine());

            Console.Write("SSL (true/false) : ");
            ssl = Convert.ToBoolean(Console.ReadLine());

            WatsonWsServer server = new WatsonWsServer(serverIp, serverPort, ssl, true, null, ClientConnected, ClientDisconnected, MessageReceived, true);

            bool runForever = true;

            while (runForever)
            {
                Console.Write("Command [? for help]: ");
                string userInput = Console.ReadLine();

                List <string> clients;
                string        ipPort;

                if (String.IsNullOrEmpty(userInput))
                {
                    continue;
                }

                switch (userInput)
                {
                case "?":
                    Console.WriteLine("Available commands:");
                    Console.WriteLine("  ?       help (this menu)");
                    Console.WriteLine("  q       quit");
                    Console.WriteLine("  cls     clear screen");
                    Console.WriteLine("  list    list clients");
                    Console.WriteLine("  send    send message to client");
                    Console.WriteLine("  kill    disconnect a client");
                    break;

                case "q":
                    runForever = false;
                    break;

                case "cls":
                    Console.Clear();
                    break;

                case "list":
                    clients = new List <string>(server.ListClients());
                    if (clients != null && clients.Count > 0)
                    {
                        Console.WriteLine("Clients");
                        foreach (string curr in clients)
                        {
                            Console.WriteLine("  " + curr);
                        }
                    }
                    else
                    {
                        Console.WriteLine("None");
                    }
                    break;

                case "send":
                    Console.Write("IP:Port: ");
                    ipPort = Console.ReadLine();
                    Console.Write("Data: ");
                    userInput = Console.ReadLine();
                    if (String.IsNullOrEmpty(userInput))
                    {
                        break;
                    }
                    server.SendAsync(ipPort, Encoding.UTF8.GetBytes(userInput));
                    break;

                case "kill":
                    Console.Write("IP:Port: ");
                    ipPort = Console.ReadLine();
                    server.KillClient(ipPort);
                    break;

                default:
                    break;
                }
            }
        }
Example #5
0
        static void Main(string[] args)
        {
            _ServerIp   = InputString("Server IP:", "localhost", true);
            _ServerPort = InputInteger("Server port:", 9000, true, true);
            _Ssl        = InputBoolean("Use SSL:", false);

            InitializeServer();
            // InitializeServerMultiple();
            Console.WriteLine("Please manually start the server");

            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":
                    StartServer();
                    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;
                }
            }
        }
        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();
            }
        }