static async Task MainAsync() { // create an instance of the socket. In this case i've used the .Net 4.5 object defined in the project INetworkSocket socket = new RconSocket(); IList <ContainerListResponse> containers = await client.Containers.ListContainersAsync( new ContainersListParameters() { Limit = 10, }); string containerMetric = ""; string ipContainer = string.Empty; foreach (ContainerListResponse f in containers) { if (f.State.ToLowerInvariant() != "running") { continue; } foreach (KeyValuePair <string, EndpointSettings> item in f.NetworkSettings.Networks) { ipContainer = item.Value.IPAddress; } containerMetric += string.Format(" & image: {0} state: {1};", f.Image, f.State); } // create the RconMessenger instance and inject the socket RconMessenger messenger = new RconMessenger(socket); // initiate the connection with the remote server bool isConnected = await messenger.ConnectAsync(ipContainer, 25575); await messenger.AuthenticateAsync("cheesesteakjimmys"); // if we fall here, we're good to go! from this point on the connection is authenticated and you can send commands // to the server string response = await messenger.ExecuteCommandAsync("/list"); string[] data = response.Substring(10, 5).Trim().Split('/'); int _maxPlayers = int.Parse(data[1]); int _players = int.Parse(data[0]); Console.WriteLine(response.Substring(10, 5).Trim()); telemetry.TrackMetric(new MetricTelemetry("Nr of players", _players)); telemetry.TrackMetric(new MetricTelemetry("Nr of maximum players", _maxPlayers)); telemetry.TrackEvent("Container is " + containerMetric); }
public static void Main(string[] args) { var stopwatch = Stopwatch.StartNew(); Console.ForegroundColor = ConsoleColor.White; Console.CursorVisible = false; AppDomain.CurrentDomain.UnhandledException += Dispose; try { _configuration = new ConfigHandler(Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + "\\Config\\config.ini"); DatabaseManager = new DatabaseManager(_configuration); LanguageManager = new LanguageManager(); SettingsManager = new SettingsManager(); FigureManager = new FigureDataManager(); RconSocket = new RconSocket(_configuration["rcon.tcp.bindip"], int.Parse(_configuration["rcon.tcp.port"]), _configuration["rcon.tcp.allowedaddr"].Split(Convert.ToChar(";"))); GameContext = new GameContext { PacketManager = new PacketManager(), PlayerController = new PlayerController() }; _connectionManager = new ConnectionHandling(int.Parse(_configuration["game.tcp.port"]), int.Parse(_configuration["game.tcp.conlimit"]), int.Parse(_configuration["game.tcp.conperip"]), _configuration["game.tcp.enablenagles"].ToLower() == "true"); new ServerStatusUpdater(); Console.WriteLine(); ServerStarted = DateTime.Now; stopwatch.Stop(); Logger.Debug("Emulator has finished loading. (took " + stopwatch.ElapsedMilliseconds / 1000 + " s, " + (stopwatch.ElapsedMilliseconds - stopwatch.ElapsedMilliseconds / 1000 * 1000) + " ms)"); } catch (Exception e) { Logger.Error(e); throw; } KeepAlive(); }
/// <summary> /// Asynchronously sends an RCON command to the server. /// Returns the response the server sent back. /// </summary> /// <param name="command">Command to send.</param> /// <returns>Server response.</returns> public async Task <string> RunCommand(string command) { INetworkSocket socket = new RconSocket(); RconMessenger messenger = new RconMessenger(socket); try { bool isConnected = await messenger.ConnectAsync(Address, Port); bool authenticated = await messenger.AuthenticateAsync(Password); if (authenticated) { return(await messenger.ExecuteCommandAsync(command)); } else { return("Authentication failed."); } } catch (SocketException exc) { return("Connection failed:\n" + exc.Message); } catch (AggregateException exc) { if (exc.InnerException.GetType() == typeof(SocketException)) { return("Connection failed:\n" + exc.InnerException); } else { return("Exception unaccounted for:\n" + exc.Message); } } catch (Exception exc) { return("Exception unaccounted for:\n" + exc.Message); } finally { messenger.CloseConnection(); socket.CloseConnection(); } }
public static void Initialize() { ServerStarted = DateTime.Now; Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(); Console.WriteLine(" ____ __ ________ _____ __"); Console.WriteLine(@" / __ \/ /_ _______/ ____/ |/ / / / /"); Console.WriteLine(" / /_/ / / / / / ___/ __/ / /|_/ / / / / "); Console.WriteLine(" / ____/ / /_/ (__ ) /___/ / / / /_/ / "); Console.WriteLine(@" /_/ /_/\__,_/____/_____/_/ /_/\____/ "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" " + PrettyVersion + " <Build " + PrettyBuild + ">"); Console.WriteLine(" http://PlusIndustry.com"); Console.WriteLine(""); Console.Title = "Loading Plus Emulator"; _defaultEncoding = Encoding.Default; Console.WriteLine(""); Console.WriteLine(""); CultureInfo = CultureInfo.CreateSpecificCulture("en-GB"); try { string projectSolutionPath = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())); _configuration = new ConfigurationData(projectSolutionPath + "\\Config\\config.ini"); var connectionString = new MySqlConnectionStringBuilder { ConnectionTimeout = 10, Database = GetConfig().data["db.name"], DefaultCommandTimeout = 30, Logging = false, MaximumPoolSize = uint.Parse(GetConfig().data["db.pool.maxsize"]), MinimumPoolSize = uint.Parse(GetConfig().data["db.pool.minsize"]), Password = GetConfig().data["db.password"], Pooling = true, Port = uint.Parse(GetConfig().data["db.port"]), Server = GetConfig().data["db.hostname"], UserID = GetConfig().data["db.username"], AllowZeroDateTime = true, ConvertZeroDateTime = true, SslMode = MySqlSslMode.None }; _manager = new DatabaseManager(connectionString.ToString()); if (!_manager.IsConnected()) { log.Error("Failed to Connect to the specified MySQL server."); Console.ReadKey(true); Environment.Exit(1); return; } log.Info("Connected to Database!"); //Reset our statistics first. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor()) { dbClient.RunQuery("TRUNCATE `catalog_marketplace_data`"); dbClient.RunQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0';"); dbClient.RunQuery("UPDATE `users` SET `online` = '0' WHERE `online` = '1'"); dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'"); } //Get the configuration & Game set. _languageManager = new LanguageManager(); _languageManager.Init(); _settingsManager = new SettingsManager(); _settingsManager.Init(); _figureManager = new FigureDataManager(); _figureManager.Init(); //Have our encryption ready. HabboEncryptionV2.Initialize(new RSAKeys()); //Make sure Rcon is connected before we allow clients to Connect. _Rcon = new RconSocket(GetConfig().data["rcon.tcp.bindip"], int.Parse(GetConfig().data["rcon.tcp.port"]), GetConfig().data["rcon.tcp.allowedaddr"].Split(Convert.ToChar(";"))); //Accept connections. _connectionManager = new ConnectionHandling(int.Parse(GetConfig().data["game.tcp.port"]), int.Parse(GetConfig().data["game.tcp.conlimit"]), int.Parse(GetConfig().data["game.tcp.conperip"]), GetConfig().data["game.tcp.enablenagles"].ToLower() == "true"); _connectionManager.Init(); _game = new Game(); _game.StartGameLoop(); TimeSpan TimeUsed = DateTime.Now - ServerStarted; Console.WriteLine(); log.Info("EMULATOR -> READY! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)"); } #pragma warning disable CS0168 // The variable 'e' is declared but never used catch (KeyNotFoundException e) #pragma warning restore CS0168 // The variable 'e' is declared but never used { log.Error("Please check your configuration file - some values appear to be missing."); log.Error("Press any key to shut down ..."); Console.ReadKey(true); Environment.Exit(1); return; } catch (InvalidOperationException e) { log.Error("Failed to initialize PlusEmulator: " + e.Message); log.Error("Press any key to shut down ..."); Console.ReadKey(true); Environment.Exit(1); return; } catch (Exception e) { log.Error("Fatal error during startup: " + e); log.Error("Press a key to exit"); Console.ReadKey(); Environment.Exit(1); } }
public async Task <RconResponse> Execute(string command) { // create an instance of the socket. In this case i've used the .Net 4.5 object defined in the project INetworkSocket socket = new RconSocket(); // create the RconMessenger instance and inject the socket RconMessenger messenger = new RconMessenger(socket); try { // initiate the connection with the remote server bool isConnected = await messenger.ConnectAsync(Address, Port); if (!isConnected) { Disconnect(socket, messenger); return(new RconResponse() { Success = false, Message = "", Error = "Failed to connect to the RCON server" }); } //Authicate with the server if (_hasPassword) { bool authenticated = await messenger.AuthenticateAsync(_password); if (!authenticated) { Disconnect(socket, messenger); return(new RconResponse() { Success = false, Message = "", Error = "Failed to authicated to RCON server" }); } } // if we fall here, we're good to go! from this point on the connection is authenticated and you can send commands // to the server //Attempt to send the command. var response = await messenger.ExecuteCommandAsync(command); //It should be something. If its empty we have failed if (string.IsNullOrEmpty(response)) { return(new RconResponse() { Success = false, Message = "", Error = "RCON returned no response." }); } //Check if the response is valid bool success = !string.IsNullOrEmpty(response); return(new RconResponse() { Success = success, Message = response, Error = "" }); } catch (Exception e) { Console.WriteLine(e); return(new RconResponse() { Success = false, Message = "", Error = "An exception occured while performing RCON: " + e.Message }); } finally { Disconnect(socket, messenger); } }