C#实现的UDP收发请求工具类实例
程序员文章站
2023-12-10 08:40:16
本文实例讲述了c#实现的udp收发请求工具类。分享给大家供大家参考,具体如下:
初始化:
listeningport = int.parse(configura...
本文实例讲述了c#实现的udp收发请求工具类。分享给大家供大家参考,具体如下:
初始化:
listeningport = int.parse(configurationmanager.appsettings["listeningport"]); sendingport = int.parse(configurationmanager.appsettings["sendingport"]); sendingip = configurationmanager.appsettings["sendingip"];
监听:
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###########"); }); }
发送:
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); } }
更多关于c#相关内容感兴趣的读者可查看本站专题:《c#程序设计之线程使用技巧总结》、《c#窗体操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#数组操作技巧总结》及《c#面向对象程序设计入门教程》
希望本文所述对大家c#程序设计有所帮助。