SoFunction
Updated on 2025-04-06

UDP request tool class instance implemented in C#

This article describes the UDP sending and receiving request tool class implemented in C#. Share it for your reference, as follows:

initialization:

ListeningPort = (["ListeningPort"]);
SendingPort = (["SendingPort"]);
SendingIp = ["SendingIp"];

monitor:

public static void Listen()
{
  (() =>
  {
    var done = false;
    var listener = new UdpClient(ListeningPort);
    var groupEP = new IPEndPoint(, ListeningPort);
    string received_data;
    byte[] receive_byte_array;
    try
    {
      _log.Error("############Service started###########");
      while (true)
      {
        receive_byte_array = (ref groupEP);
        ("Received a broadcast from {0}", ());
        received_data = Encoding.(receive_byte_array, 0, receive_byte_array.Length);
        ParseCommand(received_data);
      }
    }
    catch (Exception e)
    {
      _log.Error(e);
      (());
    }
    _log.Error("############Service stopped###########");
  });
}

send:

public static void SendCommand(string xmlCmd)
{
  try
  {
    var sending_socket = new Socket(, , );
    var sending_end_point = new IPEndPoint((SendingIp), SendingPort);
    var send_buffer = Encoding.(xmlCmd);
    sending_socket.SendTo(send_buffer, sending_end_point);
    _log.Info("[COMMAND SENT] : " + xmlCmd);
  }
  catch (Exception ex)
  {
    _log.Error(ex);
  }
}

For more information about C#, please visit the special topic of this site:Summary of thread usage techniques for C# programming》、《Summary of C# form operation skills》、《Tutorial on the usage of common C# controls》、《Summary of WinForm control usage》、《C# data structure and algorithm tutorial》、《Summary of C# array operation skills"and"Introduction to C# object-oriented programming tutorial

I hope this article will be helpful to everyone's C# programming.