Only run webserver in game

This commit is contained in:
Norbi Peti 2021-06-08 03:06:33 +02:00
parent 1256de60a7
commit 5b56d7fd43
3 changed files with 21 additions and 9 deletions

View file

@ -6,6 +6,7 @@
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
--> -->
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
<Authors>NorbiPeti</Authors>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View file

@ -4,7 +4,9 @@ using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using IllusionPlugin; using IllusionPlugin;
using TechbloxModdingAPI.App;
using TechbloxModdingAPI.Commands; using TechbloxModdingAPI.Commands;
using TechbloxModdingAPI.Utility;
using UnityEngine; using UnityEngine;
namespace TBConsole namespace TBConsole
@ -19,8 +21,19 @@ namespace TBConsole
public override void OnApplicationStart() public override void OnApplicationStart()
{ {
TechbloxModdingAPI.Main.Init(); TechbloxModdingAPI.Main.Init();
Game.Enter += async (sender, e) =>
{
while (_server?.Running ?? false)
{
Logging.LogWarning("A previous web server is still running");
_server?.Stop();
await Task.Delay(500);
}
_server = new WebServer(CommandReceived, GetCommandList); _server = new WebServer(CommandReceived, GetCommandList);
_server.Start(); _server.Start();
};
Game.Exit += (sender, e) => _server?.Stop();
} }
private string CommandReceived(string command) private string CommandReceived(string command)
@ -42,8 +55,6 @@ namespace TBConsole
} }
} }
//Console.WriteLine("Command parts: " + cmdparts.Aggregate((a, b) => a + ", " + b));
switch (cmdparts.Count) switch (cmdparts.Count)
{ {
case 1: case 1:
@ -74,7 +85,7 @@ namespace TBConsole
public override void OnApplicationQuit() public override void OnApplicationQuit()
{ {
_server.Stop(); _server?.Stop();
TechbloxModdingAPI.Main.Shutdown(); TechbloxModdingAPI.Main.Shutdown();
} }

View file

@ -7,7 +7,7 @@ namespace TBConsole
{ {
public class WebServer public class WebServer
{ {
private bool _running; public bool Running { get; private set; }
private readonly HttpListener _listener = new HttpListener(); private readonly HttpListener _listener = new HttpListener();
private readonly Func<string, string> _commandReceiver; private readonly Func<string, string> _commandReceiver;
private readonly Func<string> _commandsListSender; private readonly Func<string> _commandsListSender;
@ -20,13 +20,13 @@ namespace TBConsole
public void Start() public void Start()
{ {
_running = true; Running = true;
KeepListening(); KeepListening();
} }
public void Stop() public void Stop()
{ {
_running = false; Running = false;
_listener.Stop(); _listener.Stop();
} }
@ -34,7 +34,7 @@ namespace TBConsole
{ {
_listener.Prefixes.Add("http://localhost:8019/"); _listener.Prefixes.Add("http://localhost:8019/");
_listener.Start(); _listener.Start();
while (_running) while (Running)
{ {
try try
{ {