using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SamaPager_Client { internal class Client { internal int Port { get; set; } internal IPAddress DestinationIP { get; set; } internal UdpClient UdpStack { get; set; } private IPEndPoint serverEndPoint { get; set; } internal Client(IPAddress destinationIP, int destinationPort) { this.DestinationIP = destinationIP; this.Port = destinationPort; } internal string StartClient() { serverEndPoint = new IPEndPoint(this.DestinationIP, this.Port); try { UdpStack = new UdpClient(); return "Serving on " + serverEndPoint; } catch (Exception ex) { return $"Error ({ex.Message})"; } } internal void SendMessage(string message) { byte[] msgData = Encoding.UTF8.GetBytes(message); UdpStack.Send(msgData, msgData.Length, serverEndPoint); } internal string SendCommand(string command) { byte[] msgData = Encoding.UTF8.GetBytes(command); UdpStack.Send(msgData, msgData.Length, serverEndPoint); try { UdpStack.Client.ReceiveTimeout = 5000; IPEndPoint receiveEndPoint = serverEndPoint; byte[] receivedBytes = UdpStack.Receive(ref receiveEndPoint); return $"Server replied: {Encoding.UTF8.GetString(receivedBytes)}"; } catch(Exception ex) { return $"ERROR: {ex.Message}"; } } internal void KillClient() { this.UdpStack.Close(); } } }