SafeDispatch/TCPClientService/ClientThread.cs
2024-02-22 18:43:59 +02:00

85 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Diagnostics;
//using SafeMobileLib;
namespace WindowsService1
{
class RegistrationThread
{
int port;
public Socket socket;
public NetworkStream clientStream;
public RegistrationThread(NetworkStream _clientStream)
{
clientStream = _clientStream;
}
public void handleConnection()
{
try
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
while (true)
{
byte[] message = new byte[1024];
int result = clientStream.Read(message, 0, message.Length);
//EventLog.WriteEntry("Safemobile", "Recived data on TCP and Send on MULTICAST PACK value: " + result, EventLogEntryType.Information, 34500);
//EventLog.WriteEntry("Safemobile", "Data: X" + System.Text.Encoding.ASCII.GetString(message, 0, result).Trim() + "X", EventLogEntryType.Information, 34500);
String str = System.Text.Encoding.ASCII.GetString(message, 0, result);
if (str.Contains("PONG"))
{
Utils.WriteEventLog("Safemobile", $"Received {str}", EventLogEntryType.Information, 23456);
OnPong?.Invoke();
}
else if (str.Contains("##"))
{
System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] buf = null;
while (str.Contains("##"))
{
String send = str.Remove(str.IndexOf("##"));
send += "#";
Service1.MessageSend.Enqueue(send);
buf = enc.GetBytes(send);
Service1.UdpMulti.Send(buf, buf.Length);
str = str.Remove(0, str.IndexOf("##") + 1);
}
Service1.MessageSend.Enqueue(str);
buf = enc.GetBytes(str);
Service1.UdpMulti.Send(buf, buf.Length);
}
else
{
Service1.MessageSend.Enqueue(str);
System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] buf = enc.GetBytes(str);
Service1.UdpMulti.Send(buf, buf.Length);
}
Thread.Sleep(1);
}
}
catch (Exception ex)
{
Utils.WriteEventLog("Safemobile", "Error parsing TCP messages", EventLogEntryType.Error, 23456);
//Form1.appDead = true;
}
}
public delegate void PongDelegate();
public event PongDelegate OnPong;
}
}