melonvpn-original-cs/MelonVPNCore/GUISocketServer.cs

72 lines
2.9 KiB
C#
Raw Normal View History

2020-09-22 23:10:16 +01:00
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 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);
2021-03-19 18:40:50 +00:00
listener.Listen(32);
2020-09-22 23:10:16 +01:00
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;
2021-03-19 09:13:32 +00:00
if (data == Messages.StartingMsg) ret = ClientResponseState.Starting;
if (data == Messages.RestartingMsg) ret = ClientResponseState.Restarting;
2021-03-19 18:40:50 +00:00
if (data == Messages.RestartOnMsg) ret = ClientResponseState.RestartOn;
if (data == Messages.RestartOffMsg) ret = ClientResponseState.RestartOff;
2020-09-22 23:10:16 +01:00
Console.WriteLine(data);
if (data.StartsWith(Messages.ClientListStartMsg, StringComparison.CurrentCulture))
{
string jsonWithEof = data.Substring(Messages.ClientListStartMsg.Length);
2020-09-23 20:24:30 +01:00
string jsonData = jsonWithEof.Substring(0, jsonWithEof.Length - Messages.EOF.Length);
2020-09-22 23:10:16 +01:00
Console.WriteLine("clients: " + jsonData);
2020-09-23 20:24:30 +01:00
ConnectedClient[] clients = ClientListParser.Parse(jsonData);
2020-09-22 23:10:16 +01:00
ClientListUpdate?.Invoke(null, clients);
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
Receive?.Invoke(null, ret);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
2020-09-23 20:24:30 +01:00
Console.WriteLine("GUI socket server reached the end");
2020-09-22 23:10:16 +01:00
}
}
}