melonvpn-original-cs/MelonVPNCore/GUISocketServer.cs
2021-03-23 18:07:47 +00:00

107 lines
3.9 KiB
C#

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace MelonVPNCore
{
public static class GUISocketServer
{
public static ClientResponseState SendDataMessage(DataMessage msg) => SendCustomMessage(Messages.GetMessage(msg));
public static int reconnectTimeout = 2000;
public static DaemonClient client;
public static event EventHandler<ClientResponseState> Receive;
public static event EventHandler<ConnectedClient[]> ClientListUpdate;
private static bool waitfcl = false;
private static bool exec = true;
public static void StartServer()
{
while (exec)
{
try
{
client = new DaemonClient();
client.connectionError += Client_ConnectionError;
client.messageReceived += Client_MessageReceived;
waitfcl = true;
client.start();
while (waitfcl) Thread.Sleep(reconnectTimeout);
client.connectionError -= Client_ConnectionError;
client.messageReceived -= Client_MessageReceived;
client.Dispose();
}
catch (InvalidOperationException e)
{
Console.WriteLine(e);
}
Thread.Sleep(reconnectTimeout);
}
Console.WriteLine("GUISocketServer has reached the end.");
}
public static void oneConnect()
{
try
{
client = new DaemonClient();
client.messageReceived += Client_MessageReceived;
waitfcl = true;
client.start();
}
catch (InvalidOperationException e)
{
Console.WriteLine(e);
}
}
public static void oneDispose()
{
client.messageReceived -= Client_MessageReceived;
client.Dispose();
}
static void Client_ConnectionError(object sender, Exception e)
{
waitfcl = false;
}
static void Client_MessageReceived(object sender, string data)
{
try
{
ClientResponseState ret = ClientResponseState.None;
if (data == Messages.OnlineMsg) ret = ClientResponseState.Online;
if (data == Messages.OfflineMsg) ret = ClientResponseState.Offline;
if (data == Messages.ErrorMsg) ret = ClientResponseState.ServerError;
if (data == Messages.StartingMsg) ret = ClientResponseState.Starting;
if (data == Messages.RestartingMsg) ret = ClientResponseState.Restarting;
if (data == Messages.RestartOnMsg) ret = ClientResponseState.RestartOn;
if (data == Messages.RestartOffMsg) ret = ClientResponseState.RestartOff;
Console.WriteLine(data);
if (data.StartsWith(Messages.ClientListStartMsg, StringComparison.CurrentCulture))
{
string jsonWithEof = data.Substring(Messages.ClientListStartMsg.Length);
string jsonData = jsonWithEof.Substring(0, jsonWithEof.Length - Messages.EOF.Length);
Console.WriteLine("clients: " + jsonData);
ConnectedClient[] clients = ClientListParser.Parse(jsonData);
ClientListUpdate?.Invoke(null, clients);
}
Receive?.Invoke(null, ret);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public static ClientResponseState SendCustomMessage(string msg)
{
var toret = client?.SendCustomMessage(msg);
return (toret.HasValue) ? toret.Value : ClientResponseState.Error;
}
}
}