This article mainly introduces the C # implementation of the UDP send and receive Request tool class, combined with a specific instance of the C # for UDP requests for listening, receiving, sending and other related operations skills, the need for friends can refer to the next
The examples in this article describe the UDP send and receive request tool classes implemented by C #. Share to everyone for your reference, as follows:
Initialization
listeningport = Int. Parse (configurationmanager.appsettings["Listeningport"]); sendingport = Int. Parse (configurationmanager.appsettings["Sendingport"]); SENDINGIP = configurationmanager.appsettings["Sendingip"];
Listening:
public static void Listen () { task.run () + = { var done = false; var listener = new UdpClient (listeningport); var groupep = new IPEndPoint (Ipaddress.any, listeningport); string Received_data; Byte[] Receive_byte_array; Try { _log. Error ("########### #Service started###########"); while (true) { Receive_byte_array = listener. Receive (ref GROUPEP); Console.WriteLine ("Received a broadcast from {0}", groupep.tostring ()); Received_data = Encoding.UTF8.GetString (receive_byte_array, 0, Receive_byte_array. Length); Parsecommand (Received_data); } } catch (Exception e) { _log. Error (e); Console.WriteLine (E.tostring ()); } _log. Error ("########### #Service stopped###########");} );
Send:
public static void SendCommand (string xmlcmd) {try {var sending_socket = new Socket (addre Ssfamily.internetwork, Sockettype.dgram, PROTOCOLTYPE.UDP); var sending_end_point = new IPEndPoint (Ipaddress.parse (SENDINGIP), sendingport); var send_buffer = Encoding.UTF8.GetBytes (xmlcmd); Sending_socket. SendTo (Send_buffer, sending_end_point); _log. Info ("[COMMAND SENT]:" + xmlcmd); } catch (Exception ex) {_log. Error (ex); }}