melonvpn-original-cs/MelonVPNCore/GUISocketServer.cs
2021-03-19 16:10:14 +00:00

75 lines
3.0 KiB
C#

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace MelonVPNCore
{
public static class GUISocketServer
{
public static event EventHandler<ClientResponseState> Receive;
public static event EventHandler<ConnectedClient[]> ClientListUpdate;
public static event EventHandler<bool> RestartModeSync;
public static void StartServer()
{
IPHostEntry host = Dns.GetHostEntry("localhost");
IPAddress ipAddress = host.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 22036);
try
{
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Socket handler = listener.Accept();
string data = "";
byte[] bytes = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf(Messages.EOF, StringComparison.CurrentCulture) > -1) break;
}
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;
bool rsm = false;
if (data == Messages.RestartOnMsg) rsm = true;
if (data == Messages.RestartOffMsg) rsm = false;
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);
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
Receive?.Invoke(null, ret);
RestartModeSync?.Invoke(null, rsm);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("GUI socket server reached the end");
}
}
}