SafeDispatch/SafeMobileLIB_DLL/Helpers/RegistrationHelper.cs
2024-02-22 18:43:59 +02:00

54 lines
2.0 KiB
C#

using SafeMobileLib.Registration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace SafeMobileLib.Helpers
{
public class RegistrationHelper
{
public static Int16 TimeoutSeconds = 7;
public static String GatewayIP = "127.0.0.1";
public static async Task<RegistrationResponse> RegisterGateway(String appServerIP, Int16 registrationPort)
{
return await (Task.Factory.StartNew(() =>
{
try
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(appServerIP), registrationPort);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
GatewayIP = (client.Client.LocalEndPoint.ToString().Split(':'))[0];
UTF8Encoding encoding = new UTF8Encoding();
byte[] buffer = encoding.GetBytes("200");
clientStream.Write(buffer, 0, buffer.Length);
Utils.WriteLine($"Sent registration request to server {appServerIP}:{registrationPort}, waiting...");
byte[] message = new byte[1024];
//set read timeout to 10s
clientStream.ReadTimeout = TimeoutSeconds * 1000;
int result = clientStream.Read(message, 0, message.Length);
if (result < 1)
return new RegistrationResponse("");
String decodedString = encoding.GetString(message).Trim('\0');
return new RegistrationResponse(decodedString);
}
catch(Exception ex)
{
Utils.WriteLine("Registration exception: " + ex.ToString(), ConsoleColor.Red);
return new RegistrationResponse("");
}
}));
}
}
}