UDP_Sender.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace AggregatorFinal
  9. {
  10. class UDP_Sender
  11. {
  12. public Socket _socket;
  13. IPEndPoint _ipEndPoint;
  14. public UDP_Sender(string ip, string port)
  15. {
  16. _ipEndPoint = new IPEndPoint(IPAddress.Parse(ip.Trim()), Convert.ToInt32(port.Trim()));
  17. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  18. _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 0);
  19. }
  20. public void sendMessage(string text)
  21. {
  22. byte[] data = Encoding.ASCII.GetBytes(text);
  23. _socket.SendTo(data, data.Length, SocketFlags.None, _ipEndPoint);
  24. }
  25. public static void forwardMessage(string ip, string port, string message)
  26. {
  27. try
  28. {
  29. UDP_Sender udp_Sender = new UDP_Sender(ip, port);
  30. udp_Sender.sendMessage(message);
  31. udp_Sender._socket.Close();
  32. }
  33. catch
  34. {
  35. }
  36. }
  37. }
  38. }