public ServerInfo LoadRegisteredPlayers(ServerInfo server)
        {
            string filePath = $@"{configDir}\{server.ServerName}.players";

            if (!File.Exists(filePath))
            {
                File.Create(filePath).Close();
                return(server);
            }
            foreach (string entry in File.ReadAllLines(filePath))
            {
                if (entry.StartsWith("#") || string.IsNullOrWhiteSpace(entry))
                {
                    continue;
                }
                string[] split = entry.Split(',');
                InstanceProvider.GetServiceLogger().AppendLine($"Server \"{server.ServerName}\" Loaded registered player: {split[1]}");
                Player playerFound = server.KnownPlayers.FirstOrDefault(ply => ply.XUID == split[0]);
                if (playerFound == null)
                {
                    server.KnownPlayers.Add(new Player(split[0], split[1], DateTime.Now.Ticks.ToString(), "0", "0", split[2] == "true", split[3], split[4] == "true", true));
                    continue;
                }
                InstanceProvider.GetPlayerManager().UpdatePlayerFromCfg(split[0], split[1], split[2], split[3], split[4], server);
            }
            return(server);
        }
        public void RunServer(HostControl hostControl)
        {
            hostController = hostControl;
            string appName = serverInfo.ServerExeName.Value.Substring(0, serverInfo.ServerExeName.Value.Length - 4);

            try
            {
                if (File.Exists(serverInfo.ServerPath.Value + "\\" + serverInfo.ServerExeName.Value))
                {
                    if (MonitoredAppExists(appName))
                    {
                        Process[] processList = Process.GetProcessesByName(appName);
                        if (processList.Length != 0)
                        {
                            InstanceProvider.GetServiceLogger().AppendLine($@"Application {appName} was found running! Killing to proceed.");
                            KillProcess(processList);
                        }
                    }
                    // Fires up a new process to run inside this one
                    CreateProcess();
                }
                else
                {
                    InstanceProvider.GetServiceLogger().AppendLine("The Bedrock Server is not accessible at " + serverInfo.ServerPath.Value + "\\" + serverInfo.ServerExeName.Value + "\r\nCheck if the file is at that location and that permissions are correct.");
                    hostControl.Stop();
                }
            }
            catch (Exception e)
            {
                InstanceProvider.GetServiceLogger().AppendLine($"Error Running Bedrock Server: {e.StackTrace}");
                hostControl.Stop();
            }
        }
Exemple #3
0
 public bool SendData(byte[] bytes, NetworkMessageSource source, NetworkMessageDestination destination, NetworkMessageTypes type, NetworkMessageStatus status)
 {
     byte[] compiled = new byte[8 + bytes.Length];
     byte[] len      = BitConverter.GetBytes(4 + bytes.Length);
     Buffer.BlockCopy(len, 0, compiled, 0, 4);
     compiled[4] = (byte)source;
     compiled[5] = (byte)destination;
     compiled[6] = (byte)type;
     compiled[7] = (byte)status;
     Buffer.BlockCopy(bytes, 0, compiled, 8, bytes.Length);
     if (keepalive)
     {
         try
         {
             stream.Write(compiled, 0, compiled.Length);
             stream.Flush();
             return(true);
         }
         catch
         {
             InstanceProvider.GetServiceLogger().AppendLine("Error writing to network stream!");
             return(false);
         }
     }
     return(false);
 }
        public bool StopControl()
        {
            CurrentServerStatus = ServerStatus.Stopping;
            if (!(process is null))
            {
                InstanceProvider.GetServiceLogger().AppendLine("Sending Stop to Bedrock . Process.HasExited = " + process.HasExited.ToString());

                process.CancelOutputRead();
                process.CancelErrorRead();

                StdInStream.WriteLine("stop");
                while (!process.HasExited)
                {
                }
            }
            if (!(Worker is null))
            {
                Worker.CancelAsync();
                while (Worker.IsBusy)
                {
                    Thread.Sleep(10);
                }
                Worker.Dispose();
            }
            Worker  = null;
            process = null;
            GC.Collect();
            CurrentServerStatus = ServerStatus.Stopped;
            return(true);
        }
Exemple #5
0
        public void StartListening(int port)
        {
            IPAddress addr = IPAddress.Parse("127.0.0.1");

            InListener = InstanceProvider.InitTCPListener(addr, port);
            try
            {
                InListener.Start();
            }
            catch
            {
                InstanceProvider.GetServiceLogger().AppendLine("Error! Port is occupied and cannot be opened... Program will be killed!");
                Thread.Sleep(2000);
                Environment.Exit(1);
            }

            while (true)
            {
                try
                {
                    client = InListener.AcceptTcpClient();
                    stream = client.GetStream();
                    InstanceProvider.InitClientService(new ThreadStart(IncomingListener)).Start();
                    InstanceProvider.InitHeartbeatThread(new ThreadStart(SendBackHeatbeatSignal)).Start();
                }
                catch (ThreadStateException) { }
                catch (Exception e)
                {
                    InstanceProvider.GetServiceLogger().AppendLine(e.ToString());
                }
            }
            //listener.Stop();
        }
        public static async Task <bool> CheckUpdates()
        {
            InstanceProvider.GetServiceLogger().AppendLine("Checking MCS Version and fetching update if needed...");
            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/apng,*/*;q=0.8");
            client.DefaultRequestHeaders.Add("Accept-Language", "en-GB,en;q=0.9,en-US;q=0.8");
            client.DefaultRequestHeaders.Add("Connection", "keep-alive");
            client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
            client.DefaultRequestHeaders.Add("Pragma", "no-cache");
            client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko; Google Page Speed Insights) Chrome/27.0.1453 Safari/537.36");
            client.Timeout = new TimeSpan(0, 0, 2);

            string content = FetchHTTPContent(client).Result;

            if (content == null) // This really doesn't fail often. Give it one more try or fail.
            {
                Thread.Sleep(500);
                content = await FetchHTTPContent(client);
            }
            if (content == null)
            {
                return(false);
            }
            string pattern = @"(https://minecraft.azureedge.net/bin-win/bedrock-server-)(.*)(\.zip)";
            Regex  regex   = new Regex(pattern, RegexOptions.IgnoreCase);
            Match  m       = regex.Match(content);

            if (!m.Success)
            {
                InstanceProvider.GetServiceLogger().AppendLine("Checking for updates failed. Check website functionality!");
                return(false);
            }
            string downloadPath = m.Groups[0].Value;
            string version      = m.Groups[2].Value;

            client.Dispose();

            if (File.Exists($@"{Program.ServiceDirectory}\Server\bedrock_ver.ini"))
            {
                string LocalVer = File.ReadAllText($@"{Program.ServiceDirectory}\Server\bedrock_ver.ini");
                if (LocalVer != version)
                {
                    InstanceProvider.GetServiceLogger().AppendLine($"New version detected! Now fetching from {downloadPath}...");
                    VersionChanged = true;
                    FetchBuild(downloadPath, version).Wait();
                    File.WriteAllText($@"{Program.ServiceDirectory}\Server\bedrock_ver.ini", version);
                    return(true);
                }
            }
            else
            {
                InstanceProvider.GetServiceLogger().AppendLine("Version ini file missing, fetching build to recreate...");
                FetchBuild(downloadPath, version).Wait();
                File.WriteAllText($@"{Program.ServiceDirectory}\Server\bedrock_ver.ini", version);
                return(true);
            }
            return(false);
        }
        public static async Task FetchBuild(string path, string version)
        {
            string ZipDir = $@"{Program.ServiceDirectory}\Server\MCSFiles\Update_{version}.zip";

            if (!Directory.Exists($@"{Program.ServiceDirectory}\Server\MCSFiles"))
            {
                Directory.CreateDirectory($@"{Program.ServiceDirectory}\Server\MCSFiles");
            }
            if (File.Exists(ZipDir))
            {
                File.Delete(ZipDir);
            }
            if ((string)InstanceProvider.GetHostInfo().GetGlobalValue("AcceptedMojangLic") == "false")
            {
                InstanceProvider.GetServiceLogger().AppendLine("------First time download detected------\n");
                InstanceProvider.GetServiceLogger().AppendLine("You will need to agree to the Minecraft End User License Agreement");
                InstanceProvider.GetServiceLogger().AppendLine("in order to continue. Visit https://account.mojang.com/terms");
                InstanceProvider.GetServiceLogger().AppendLine("to view terms. Type \"Yes\" and press enter to confirm that");
                InstanceProvider.GetServiceLogger().AppendLine("you agree to said terms.");
                Console.Write("Do you agree to the terms? ");
                Console.Out.Flush();
                if (Console.ReadLine() != "Yes")
                {
                    return;
                }
                InstanceProvider.GetHostInfo().SetGlobalProperty("AcceptedMojangLic", "true");
                InstanceProvider.GetConfigManager().SaveGlobalFile();
                InstanceProvider.GetServiceLogger().AppendLine("Now downloading latest build of Minecraft Bedrock Server. Please wait...");
            }
            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, path))
                {
                    using (Stream contentStream = await(await httpClient.SendAsync(request)).Content.ReadAsStreamAsync(), stream = new FileStream(ZipDir, FileMode.Create, FileAccess.Write, FileShare.None, 256000, true))
                    {
                        try
                        {
                            await contentStream.CopyToAsync(stream);
                        }
                        catch (Exception e)
                        {
                            InstanceProvider.GetServiceLogger().AppendLine($"Download zip resulted in error: {e.StackTrace}");
                        }
                        httpClient.Dispose();
                        request.Dispose();
                        contentStream.Dispose();
                    }
                }
            }
        }
 private static async Task <string> FetchHTTPContent(HttpClient client)
 {
     try
     {
         return(await client.GetStringAsync("https://www.minecraft.net/en-us/download/server/bedrock"));
     }
     catch (HttpRequestException e)
     {
         InstanceProvider.GetServiceLogger().AppendLine($"Error! Updater timed out, could not fetch current build!");
     }
     catch (Exception e)
     {
         InstanceProvider.GetServiceLogger().AppendLine($"Updater resulted in error: {e.Message}\n{e.InnerException}\n{e.StackTrace}");
     }
     return(null);
 }
 private void KillProcess(Process[] processList)
 {
     foreach (Process process in processList)
     {
         try
         {
             process.Kill();
             Thread.Sleep(1000);
             InstanceProvider.GetServiceLogger().AppendLine($@"App {serverInfo.ServerExeName.Value.Substring(0, serverInfo.ServerExeName.Value.Length - 4)} killed!");
         }
         catch (Exception e)
         {
             InstanceProvider.GetServiceLogger().AppendLine($"Killing proccess resulted in error: {e.StackTrace}");
         }
     }
 }
 private bool MonitoredAppExists(string monitoredAppName)
 {
     try
     {
         Process[] processList = Process.GetProcessesByName(monitoredAppName);
         if (processList.Length == 0)
         {
             return(false);
         }
         else
         {
             return(true);
         }
     }
     catch (Exception ex)
     {
         InstanceProvider.GetServiceLogger().AppendLine("ApplicationWatcher MonitoredAppExists Exception: " + ex.StackTrace);
         return(true);
     }
 }
 public void ApplicationWatchdogMonitor()
 {
     while (WatchdogThread.IsAlive)
     {
         string appName = serverInfo.ServerExeName.Value.Substring(0, serverInfo.ServerExeName.Value.Length - 4);
         if (!MonitoredAppExists(appName) && CurrentServerStatus == ServerStatus.Starting)
         {
             hostController.RequestAdditionalTime(TimeSpan.FromSeconds(30));
             StartControl(hostController);
             InstanceProvider.GetServiceLogger().AppendLine($"Recieved start signal for server {serverInfo.ServerName}.");
         }
         while (MonitoredAppExists(appName) && CurrentServerStatus == ServerStatus.Started)
         {
             Thread.Sleep(5000);
         }
         if (MonitoredAppExists(appName) && CurrentServerStatus == ServerStatus.Stopping)
         {
             InstanceProvider.GetServiceLogger().AppendLine($"BedrockService signaled stop to application {appName}.");
             InstanceProvider.GetServiceLogger().AppendLine("Stopping...");
             StopControl();
             while (CurrentServerStatus == ServerStatus.Stopping)
             {
                 Thread.Sleep(250);
             }
         }
         if (!MonitoredAppExists(appName) && CurrentServerStatus == ServerStatus.Started)
         {
             StopControl();
             InstanceProvider.GetServiceLogger().AppendLine($"Started application {appName} was not found in running processes... Resarting {appName}.");
             StartControl(hostController);
         }
         if (!MonitoredAppExists(appName) && CurrentServerStatus == ServerStatus.Stopped)
         {
             InstanceProvider.GetServiceLogger().AppendLine("Server stopped successfully.");
         }
         while (!MonitoredAppExists(appName) && CurrentServerStatus == ServerStatus.Stopped)
         {
             Thread.Sleep(1000);
         }
     }
 }
        public ServerInfo LoadPlayerDatabase(ServerInfo server)
        {
            string filePath = $@"{configDir}\{server.ServerName}.playerdb";

            if (!File.Exists(filePath))
            {
                File.Create(filePath).Close();
                return(server);
            }
            foreach (string entry in File.ReadAllLines(filePath))
            {
                if (entry.StartsWith("#") || string.IsNullOrWhiteSpace(entry))
                {
                    continue;
                }
                string[] split = entry.Split(',');
                InstanceProvider.GetServiceLogger().AppendLine($"Server \"{server.ServerName}\" Loaded known player: {split[1]}");
                server.KnownPlayers.Add(new Player(split[0], split[1], split[2], split[3], split[4]));
            }
            return(server);
        }
Exemple #13
0
 public void SendBackHeatbeatSignal()
 {
     InstanceProvider.GetServiceLogger().AppendLine("HeartBeatSender started.");
     while (keepalive)
     {
         heartbeatRecieved = false;
         while (!heartbeatRecieved)
         {
             Thread.Sleep(100);
             heartbeatFailTimeout++;
             if (heartbeatFailTimeout > heartbeatFailTimeoutLimit)
             {
                 if (!firstHeartbeatRecieved)
                 {
                     try
                     {
                         SendData(NetworkMessageSource.Service, NetworkMessageDestination.Client, NetworkMessageTypes.Heartbeat);
                         heartbeatFailTimeout = 0;
                     }
                     catch
                     {
                         InstanceProvider.GetServiceLogger().AppendLine("HeartBeatSender exited.");
                         return;
                     }
                 }
                 DisconnectClient();
                 InstanceProvider.GetServiceLogger().AppendLine("HeartBeatSender exited.");
                 return;
             }
         }
         heartbeatRecieved    = false;
         heartbeatFailTimeout = 0;
         SendData(NetworkMessageSource.Service, NetworkMessageDestination.Client, NetworkMessageTypes.Heartbeat);
         Thread.Sleep(3000);
     }
     InstanceProvider.GetServiceLogger().AppendLine("HeartBeatSender exited.");
 }
        public bool LoadConfigs()
        {
            bool loading = true;

            if (!Directory.Exists(configDir))
            {
                Directory.CreateDirectory(configDir);
            }
            if (File.Exists($@"{configDir}\..\bedrock_ver.ini"))
            {
                loadedVersion = File.ReadAllText($@"{configDir}\..\bedrock_ver.ini");
            }

            string[] files          = Directory.GetFiles(configDir, "*.conf");
            string   globFileResult = null;

            foreach (string file in files)
            {
                if (file.EndsWith("Globals.conf"))
                {
                    globFileResult = file;
                    InstanceProvider.GetServiceLogger().AppendLine("Loading Globals...");
                    InstanceProvider.GetHostInfo().SetGlobalsDefault();
                    string[] lines = File.ReadAllLines(file);
                    foreach (string line in lines)
                    {
                        if (!line.StartsWith("#") && !string.IsNullOrEmpty(line))
                        {
                            string[] split = line.Split('=');
                            if (split.Length == 1)
                            {
                                split[1] = "";
                            }
                            InstanceProvider.GetHostInfo().GetGlobals().First(prop => prop.KeyName == split[0]).Value = split[1];
                        }
                    }
                }
            }
            if (globFileResult == null)
            {
                InstanceProvider.GetHostInfo().SetGlobalsDefault();
                InstanceProvider.GetServiceLogger().AppendLine("Globals.conf was not found. Loaded defaults and saved to file.");
                SaveGlobalFile();
            }
            InstanceProvider.GetHostInfo().ClearServerInfos();
            ServerInfo serverInfo = new ServerInfo();

            serverInfo.InitDefaults();
            while (loading)
            {
                foreach (string file in files)
                {
                    FileInfo FInfo = new FileInfo(file);
                    if (FInfo.Name == "Globals.conf")
                    {
                        continue;
                    }
                    serverInfo = new ServerInfo();
                    serverInfo.InitDefaults();
                    serverInfo.FileName      = FInfo.Name;
                    serverInfo.ServerVersion = loadedVersion;
                    string[] linesArray = File.ReadAllLines(file);
                    foreach (string line in linesArray)
                    {
                        if (!line.StartsWith("#") && !string.IsNullOrEmpty(line))
                        {
                            string[] split = line.Split('=');
                            if (split.Length == 1)
                            {
                                split = new string[] { split[0], "" };
                            }
                            Property SrvProp = serverInfo.ServerPropList.FirstOrDefault(prop => prop.KeyName == split[0]);
                            if (SrvProp != null)
                            {
                                serverInfo.SetServerProp(split[0], split[1]);
                            }
                            switch (split[0])
                            {
                            case "server-name":
                                InstanceProvider.GetServiceLogger().AppendLine($"Loading ServerInfo for server {split[1]}...");
                                serverInfo.ServerName = split[1];
                                LoadPlayerDatabase(serverInfo);
                                LoadRegisteredPlayers(serverInfo);
                                break;

                            case "AddStartCmd":
                                serverInfo.StartCmds.Add(new StartCmdEntry(split[1]));
                                break;

                            case "ServerPath":
                                serverInfo.ServerPath.Value = split[1];
                                break;

                            case "ServerExeName":
                                serverInfo.ServerExeName.Value = split[1];
                                break;

                            case "BackupPath":
                                serverInfo.BackupPath.Value = split[1];
                                break;

                            case "LogToFile":
                                serverInfo.LogToFileEnabled.Value = split[1];
                                break;

                            case "AdvancedBackup":
                                serverInfo.AdvancedBackup.Value = split[1];
                                break;

                            case "MaxBackupCount":
                                serverInfo.MaxBackupCount.Value = split[1];
                                break;
                            }
                        }
                    }
                    InstanceProvider.GetHostInfo().GetServerInfos().Add(serverInfo);
                }
                if (InstanceProvider.GetHostInfo().GetServerInfos().Count == 0)
                {
                    SaveServerProps(serverInfo, true);
                    files = Directory.GetFiles(configDir, "*.conf");
                }
                else
                {
                    loading = false;
                }
            }
            return(true);
        }
        public bool Backup()
        {
            try
            {
                FileInfo exe = new FileInfo(serverInfo.ServerPath.Value + serverInfo.ServerExeName.Value);

                if (serverInfo.BackupPath.Value.Length > 0)
                {
                    DirectoryInfo serverDir = new DirectoryInfo(serverInfo.ServerPath.Value);
                    DirectoryInfo worldsDir = new DirectoryInfo($@"{serverInfo.ServerPath.Value}\worlds");
                    DirectoryInfo backupDir = new DirectoryInfo($@"{serverInfo.BackupPath.Value}\{serverInfo.ServerName}");
                    if (!Directory.Exists(backupDir.FullName))
                    {
                        Directory.CreateDirectory($@"{serverInfo.BackupPath.Value}\{serverInfo.ServerName}");
                    }
                    int dirCount = backupDir.GetDirectories().Length;                  // this line creates a new int with a value derived from the number of directories found in the backups folder.
                    try                                                                // use a try catch any time you know an error could occur.
                    {
                        if (dirCount >= int.Parse(serverInfo.MaxBackupCount.Value))    // Compare the directory count with the value set in the config. Values from config are stored as strings, and therfore must be converted to integer first for compare.
                        {
                            string pattern = $@"Backup_(.*)$";                         // This is a regular expression pattern. If you would like to know more, Grab notepad++ and play with regex search, a lot of guides out there.
                            Regex  reg     = new Regex(pattern);                       // Creates a new Regex class with our pattern loaded.

                            List <long> Dates = new List <long>();                     // creates a new list long integer array named Dates, and initializes it.
                            foreach (DirectoryInfo dir in backupDir.GetDirectories())  // Loop through the array of directories in backup folder. In this "foreach" loop, we name each entry in the array "dir" and then do something to it.
                            {
                                if (reg.IsMatch(dir.Name))                             // Using regex.IsMatch will return true if the pattern matches the name of the folder we are working with.
                                {
                                    Match match = reg.Match(dir.Name);                 // creates an instance of the match to work with.
                                    Dates.Add(Convert.ToInt64(match.Groups[1].Value)); // if it was a match, we then pull the number we saved in the (.*) part of the pattern from the groups method in the match. Groups saves the entire match first, followed by anthing saved in parentheses. Because we need to compare dates, we must convert the string to an integer.
                                }
                            }
                            long OldestDate = 0;            // Create a new int to store the oldest date in.
                            foreach (long date in Dates)    // for each date in the Dates array....
                            {
                                if (OldestDate == 0)        // if this is the first entry in Dates, OldestDate will still be 0. Set it to a date so compare can happen.
                                {
                                    OldestDate = date;      // OldestDate now equals date.
                                }
                                else if (date < OldestDate) // If now the next entry in Dates is a smaller number than the previously set OldestDate, reset OldestDate to date.
                                {
                                    OldestDate = date;      // OldestDate now equals date.
                                }
                            }
                            Directory.Delete($@"{backupDir}\Backup_{OldestDate}", true); // After running through all directories, this string $@"{backupDir}\Backup_{OldestDate}" should now represent the folder that has the lowest/oldest date. Delete it. Supply the "true" after the directory string to enable recusive mode, removing all files and folders.
                        }
                    }
                    catch (Exception e)                                                                                                      // catch all exceptions here.
                    {
                        if (e.GetType() == typeof(FormatException))                                                                          // if the exception is equal a type of FormatException, Do the following... if this was a IOException, they would not match.
                        {
                            InstanceProvider.GetServiceLogger().AppendLine("Error in Config! MaxBackupCount must be nothing but a number!"); // this exception will be thrown if the string could not become a number (i.e. of there was a letter in the mix).
                        }
                    }

                    var targetDirectory = backupDir.CreateSubdirectory($"Backup_{DateTime.Now:yyyyMMddhhmmss}");
                    InstanceProvider.GetServiceLogger().AppendLine($"Backing up files for server {serverInfo.ServerName}. Please wait!");
                    if (serverInfo.AdvancedBackup.Value == "false")
                    {
                        CopyFilesRecursively(worldsDir, targetDirectory);
                    }
                    else if (serverInfo.AdvancedBackup.Value == "true")
                    {
                        CopyFilesRecursively(serverDir, targetDirectory);
                    }
                    return(true);
                }
            }
            catch (Exception e)
            {
                InstanceProvider.GetServiceLogger().AppendLine($"Error with Backup: {e.StackTrace}");
                return(false);
            }
            return(false);
        }
Exemple #16
0
        private void IncomingListener()
        {
            keepalive = true;
            InstanceProvider.GetServiceLogger().AppendLine("Established connection! Listening for incoming packets!");
            int AvailBytes = 0;
            int byteCount  = 0;

            while (InstanceProvider.GetClientServiceAlive())
            {
                try
                {
                    byte[] buffer = new byte[4];
                    AvailBytes = client.Client.Available;
                    while (AvailBytes != 0) // Recieve data from client.
                    {
                        byteCount = stream.Read(buffer, 0, 4);
                        int expectedLen = BitConverter.ToInt32(buffer, 0);
                        buffer    = new byte[expectedLen];
                        byteCount = stream.Read(buffer, 0, expectedLen);
                        NetworkMessageSource      msgSource = (NetworkMessageSource)buffer[0];
                        NetworkMessageDestination msgDest   = (NetworkMessageDestination)buffer[1];
                        NetworkMessageTypes       msgType   = (NetworkMessageTypes)buffer[2];
                        NetworkMessageStatus      msgStatus = (NetworkMessageStatus)buffer[3];
                        string   data      = GetOffsetString(buffer);
                        string[] dataSplit = null;
                        switch (msgDest)
                        {
                        case NetworkMessageDestination.Server:

                            JsonParser message;
                            switch (msgType)
                            {
                            case NetworkMessageTypes.PropUpdate:

                                message = JsonParser.Deserialize(data);
                                List <Property> propList = message.Value.ToObject <List <Property> >();
                                Property        prop     = propList.First(p => p.KeyName == "server-name");
                                InstanceProvider.GetBedrockServer(prop.Value).serverInfo.ServerPropList = propList;
                                InstanceProvider.GetConfigManager().SaveServerProps(InstanceProvider.GetBedrockServer(prop.Value).serverInfo, true);
                                InstanceProvider.GetConfigManager().LoadConfigs();
                                InstanceProvider.GetBedrockServer(prop.Value).CurrentServerStatus = BedrockServer.ServerStatus.Stopping;
                                while (InstanceProvider.GetBedrockServer(prop.Value).CurrentServerStatus == BedrockServer.ServerStatus.Stopping)
                                {
                                    Thread.Sleep(100);
                                }
                                InstanceProvider.GetBedrockServer(prop.Value).StartControl(InstanceProvider.GetBedrockService()._hostControl);
                                SendData(NetworkMessageSource.Server, NetworkMessageDestination.Client, NetworkMessageTypes.PropUpdate);

                                break;

                            case NetworkMessageTypes.Restart:

                                RestartServer(data, false);
                                break;

                            case NetworkMessageTypes.Backup:

                                RestartServer(data, true);
                                break;

                            case NetworkMessageTypes.Command:

                                dataSplit = data.Split(';');
                                InstanceProvider.GetBedrockServer(dataSplit[0]).StdInStream.WriteLine(dataSplit[1]);
                                InstanceProvider.GetServiceLogger().AppendLine($"Sent command {dataSplit[1]} to stdInput stream");

                                break;
                            }
                            break;

                        case NetworkMessageDestination.Service:
                            switch (msgType)
                            {
                            case NetworkMessageTypes.Connect:

                                InstanceProvider.GetHostInfo().ServiceLog = InstanceProvider.GetServiceLogger().Log;
                                string jsonString    = JsonParser.Serialize(JsonParser.FromValue(InstanceProvider.GetHostInfo()));
                                byte[] stringAsBytes = GetBytes(jsonString);
                                SendData(stringAsBytes, NetworkMessageSource.Service, NetworkMessageDestination.Client, NetworkMessageTypes.Connect);
                                heartbeatRecieved = false;

                                break;

                            case NetworkMessageTypes.Disconnect:

                                DisconnectClient();

                                break;

                            case NetworkMessageTypes.Heartbeat:

                                if (InstanceProvider.GetHeartbeatThreadAlive())
                                {
                                    heartbeatRecieved = true;
                                }
                                else
                                {
                                    InstanceProvider.InitHeartbeatThread(new ThreadStart(SendBackHeatbeatSignal)).Start();
                                    Thread.Sleep(500);
                                    heartbeatRecieved = true;
                                }

                                break;

                            case NetworkMessageTypes.ConsoleLogUpdate:

                                StringBuilder srvString = new StringBuilder();
                                string[]      split     = data.Split('|');
                                for (int i = 0; i < split.Length; i++)
                                {
                                    dataSplit = split[i].Split(';');
                                    string srvName = dataSplit[0];
                                    int    srvTextLen;
                                    int    clientCurLen;
                                    int    loop;
                                    if (srvName != "Service")
                                    {
                                        ServerLogger srvText = InstanceProvider.GetBedrockServer(srvName).serverInfo.ConsoleBuffer;
                                        srvTextLen   = srvText.Count();
                                        clientCurLen = int.Parse(dataSplit[1]);
                                        loop         = clientCurLen;
                                        while (loop < srvTextLen)
                                        {
                                            srvString.Append($"{srvName};{srvText.FromIndex(loop)};{loop}|");
                                            loop++;
                                        }
                                    }
                                    else
                                    {
                                        ServiceLogger srvText = InstanceProvider.GetServiceLogger();
                                        srvTextLen   = srvText.Count();
                                        clientCurLen = int.Parse(dataSplit[1]);
                                        loop         = clientCurLen;
                                        while (loop < srvTextLen)
                                        {
                                            srvString.Append($"{srvName};{srvText.FromIndex(loop)};{loop}|");
                                            loop++;
                                        }
                                    }
                                }
                                if (srvString.Length > 1)
                                {
                                    srvString.Remove(srvString.Length - 1, 1);
                                    stringAsBytes = GetBytes(srvString.ToString());
                                    SendData(stringAsBytes, NetworkMessageSource.Server, NetworkMessageDestination.Client, NetworkMessageTypes.ConsoleLogUpdate);
                                }
                                break;
                            }
                            break;
                        }
                        AvailBytes = client.Client.Available;
                    }
                    Thread.Sleep(200);
                }
                catch (OutOfMemoryException)
                {
                    InstanceProvider.GetServiceLogger().AppendLine("");
                }
                catch (ObjectDisposedException e)
                {
                    InstanceProvider.GetServiceLogger().AppendLine("Client was disposed! Killing thread...");
                    break;
                }
                catch (ThreadAbortException) { }

                catch (JsonException e)
                {
                    InstanceProvider.GetServiceLogger().AppendLine($"Error parsing json array: {e.Message}");
                    InstanceProvider.GetServiceLogger().AppendLine($"Stacktrace: {e.InnerException}");
                }
                catch (Exception e)
                {
                    //InstanceProvider.GetServiceLogger().AppendLine($"Error: {e.Message} {e.StackTrace}");
                    //InstanceProvider.GetServiceLogger().AppendLine($"Error: {e.Message}: {AvailBytes}, {byteCount}\n{e.StackTrace}");
                }
                AvailBytes = client.Client.Available;
                if (InstanceProvider.GetClientService().ThreadState == ThreadState.Aborted)
                {
                    keepalive = false;
                }
            }
            InstanceProvider.GetServiceLogger().AppendLine("IncomingListener thread exited.");
        }