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 ( AddressFamily.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); } }
Above is the C # UDP send and Receive Request tool class introduction content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!