SafeDispatch/TCPServerService/UdpMulticast.cs

241 lines
8.3 KiB
C#
Raw Normal View History

2024-02-22 16:43:59 +00:00
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Security.Cryptography;
using System.IO;
using System.Diagnostics;
namespace TCPServerService
{
public class UdpMulticast
{
private Socket s;
private Thread listenThread;
private string mcastGroup;
private int port;
private bool working = false;
private bool useThreadPool = false;
private string localIP = null;
public UdpMulticast(string mcastGroup, int port)
{
this.mcastGroup = mcastGroup;
this.port = port;
}
private void Listen_pool(object a)
{
Listen();
}
private void Listen()
{
while (working)
{
try
{
int recv = 0; ;
byte[] b = new byte[2048];
Thread.Sleep(1);
if (s != null)
recv = s.Receive(b);
else
break;//break if socket == null
if (recv == 0)
continue;//continue if return nr bytes == 0
if (OnNewDataRecv != null)
{
byte[] tmp = new byte[recv];
for (int i = 0; i < recv; i++)
{
tmp[i] = b[i];
}
byte[] decByte = Encryption.Decrypt(tmp);
if (this.OnNewDataRecv != null)
this.OnNewDataRecv(decByte, decByte.Length);
}
if (s == null)
{
break;
}
}
catch (SocketException ex)
{
Utils.WriteEventLog(Program.COMPANY, "UdpMulticast Listen SOCKET EXCEPTION " + ex.ToString(), EventLogEntryType.Error, 23456);
//StartListen(localIP);
break;
}
catch (ThreadAbortException ex)
{
Utils.WriteEventLog(Program.COMPANY, "UdpMulticast Listen Thread Abort EXCEPTION " + ex.ToString(), EventLogEntryType.Error, 23456);
//StartListen(localIP);
break;
}
catch (Exception ex)
{
Utils.WriteEventLog(Program.COMPANY, "UdpMulticast Listen Exception" + ex.ToString(), EventLogEntryType.Error, 23456);
//StartListen(localIP);
}
}
}
public delegate void newData4Send(byte[] data, int dataLen);
public event newData4Send OnNewDataRecv;
public bool StartListen(string localIP = null)
{
bool ret = false;
working = true;
this.localIP = localIP;
IPAddress myIP = !string.IsNullOrWhiteSpace(localIP) ? IPAddress.Parse(localIP) : getPreferedIPAdress();
try
{
try
{
if (s != null)
{
s.Close();
s.Disconnect(false);
}
}
catch(Exception ex)
{
Utils.WriteEventLog(Program.COMPANY, "StartListen multicast error:" + ex.ToString(), EventLogEntryType.Error, 34500);
}
if (s == null)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
if (s != null)
{
Utils.WriteEventLog(Program.COMPANY, "PORT multi cast :" + port, EventLogEntryType.Information, 34500);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
s.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.MulticastTimeToLive, int.Parse("1"));
listenThread = new Thread(new ThreadStart(Listen));
listenThread.IsBackground = true;
}
if (listenThread != null)
listenThread.Start();
ret = true;
Utils.WriteEventLog("Safemobile",
$"++++++++++++++++++++++++++++++++++++++++++\nUdpMulticast bind on {mcastGroup}:{port} Ethernet: {myIP}\n++++++++++++++++++++++++++++++++++++++++++",
EventLogEntryType.Information, 23456);
}
catch (Exception ex)
{
Utils.WriteEventLog(Program.COMPANY, "Ex:" + ex.ToString(), EventLogEntryType.Error, 23456);
}
return ret;
}
public static IPAddress getPreferedIPAdress()
{
IPAddress localIP = IPAddress.Parse("127.0.0.1");
Socket socket = null;
try
{
using (socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("10.0.2.4", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIP = endPoint.Address;
}
}
catch (Exception ex)
{
Utils.WriteLine(ex.ToString(), ConsoleColor.DarkRed);
}
finally
{
if (socket != null)
socket.Dispose();
}
return localIP;
}
public void Send(byte[] data, int len)
{
if (s == null)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
if (s != null)
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(mcastGroup), port);
byte[] encByte = Encryption.Encrypt(data);
s.SendTo(encByte, encByte.Length, SocketFlags.None, ipep);
}
else Utils.WriteEventLog(Program.COMPANY, "s is NULL", EventLogEntryType.Error, 23456);
}
public void Send_decoded(byte[] data, int len)
{
if (s == null)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
if (s != null)
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(mcastGroup), port);
s.SendTo(data, data.Length, SocketFlags.None, ipep);
}
else Utils.WriteEventLog(Program.COMPANY, "s is NULL", EventLogEntryType.Error, 23456);
}
}
static public class Encryption
{
static byte[] bytes = ASCIIEncoding.ASCII.GetBytes("SafeMobi"); //DES 64bit !
static public byte[] Encrypt(byte[] inputArray)
{
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
cryptoStream.Write(inputArray, 0, inputArray.Length);
cryptoStream.Close(); memoryStream.Close();
return memoryStream.ToArray();
}
static public byte[] Decrypt(byte[] DataToDecrypt)
{
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Write);
cryptoStream.Write(DataToDecrypt, 0, DataToDecrypt.Length);
cryptoStream.Close(); memoryStream.Close();
return memoryStream.ToArray();
}
}
}