C# UdpClient使用
客户端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | public class UdpClientManager { //接收数据事件 public Action< string > recvMessageEvent = null ; //发送结果事件 public Action< int > sendResultEvent = null ; //本地监听端口 public int localPort = 0; private UdpClient udpClient = null ; public UdpClientManager( int localPort) { if (localPort < 0 || localPort > 65535) throw new ArgumentOutOfRangeException( "localPort is out of range" ); this .localPort = localPort; } public void Start() { while ( true ) { try { udpClient = new UdpClient(localPort, AddressFamily.InterNetwork); //指定本地监听port ReceiveMessage(); break ; } catch (Exception) { Thread.Sleep(100); } } } private async void ReceiveMessage() { while ( true ) { if (udpClient == null ) return ; try { UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer); if (recvMessageEvent != null ) recvMessageEvent(message); } catch (Exception ex) { } } } //单播 public async void SendMessageByUnicast( string message, string destHost, int destPort) { if ( string .IsNullOrEmpty(message)) throw new ArgumentNullException( "message cant not null" ); if (udpClient == null ) throw new ArgumentNullException( "udpClient cant not null" ); if ( string .IsNullOrEmpty(destHost)) throw new ArgumentNullException( "destHost cant not null" ); if (destPort < 0 || destPort > 65535) throw new ArgumentOutOfRangeException( "destPort is out of range" ); byte [] buffer = Encoding.UTF8.GetBytes(message); int len = 0; for ( int i = 0; i < 3; i++) { try { len = await udpClient.SendAsync(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(destHost), destPort)); } catch (Exception) { len = 0; } if (len <= 0) Thread.Sleep(100); else break ; } if (sendResultEvent != null ) sendResultEvent(len); } public void CloseUdpCliend() { if (udpClient == null ) throw new ArgumentNullException( "udpClient cant not null" ); try { udpClient.Client.Shutdown(SocketShutdown.Both); } catch (Exception) { } udpClient.Close(); udpClient = null ; } } |
服务器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | public class UdpServiceManager { private readonly string broadCastHost = "255.255.255.255" ; //接收数据事件 public Action< string > recvMessageEvent = null ; //发送结果事件 public Action< int > sendResultEvent = null ; //本地host private string localHost = "" ; //本地port private int localPort = 0; private UdpClient udpClient = null ; public UdpServiceManager( string localHost, int localPort) { if ( string .IsNullOrEmpty(localHost)) throw new ArgumentNullException( "localHost cant not null" ); if (localPort < 0 || localPort > 65535) throw new ArgumentOutOfRangeException( "localPort is out of range" ); this .localHost = localHost; this .localPort = localPort; } public void Start() { while ( true ) { try { udpClient = new UdpClient( new IPEndPoint(IPAddress.Parse(localHost), localPort)); //绑定本地host和port ReceiveMessage(); break ; } catch (Exception) { Thread.Sleep(100); } } } private async void ReceiveMessage() { while ( true ) { if (udpClient == null ) return ; try { UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer); if (recvMessageEvent != null ) recvMessageEvent(message); } catch (Exception) { } } } //单播 public async void SendMessageByUnicast( string message, string destHost, int destPort) { if ( string .IsNullOrEmpty(message)) throw new ArgumentNullException( "message cant not null" ); if ( string .IsNullOrEmpty(destHost)) throw new ArgumentNullException( "destHost cant not null" ); if (destPort < 0 || destPort > 65535) throw new ArgumentOutOfRangeException( "destPort is out of range" ); if (udpClient == null ) throw new ArgumentNullException( "udpClient cant not null" ); byte [] buffer = Encoding.UTF8.GetBytes(message); int len = 0; for ( int i = 0; i < 3; i++) { try { len = await udpClient.SendAsync(buffer, buffer.Length, destHost, destPort); } catch (Exception) { len = 0; } if (len <= 0) Thread.Sleep(100); else break ; } if (sendResultEvent != null ) sendResultEvent(len); } //广播 public async void SendMessageByBroadcast( string message) { if ( string .IsNullOrEmpty(message)) throw new ArgumentNullException( "message cant not null" ); if (udpClient == null ) throw new ArgumentNullException( "udpClient cant not null" ); byte [] buffer = Encoding.UTF8.GetBytes(message); int len = 0; for ( int i = 0; i < 3; i++) { try { len = await udpClient.SendAsync(buffer, buffer.Length, broadCastHost, localPort); } catch (Exception ex) { len = 0; } if (len <= 0) Thread.Sleep(100); else break ; } if (sendResultEvent != null ) sendResultEvent(len); } public void CloseUdpCliend() { if (udpClient == null ) throw new ArgumentNullException( "udpClient cant not null" ); try { udpClient.Client.Shutdown(SocketShutdown.Both); } catch (Exception) { } udpClient.Close(); udpClient = null ; } } |
多播方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | public class UdpClientManager { //接收数据事件 public Action< string > recvMessageEvent = null ; //发送结果事件 public Action< int > sendResultEvent = null ; //本地监听端口 public int localPort = 0; //组播地址 public string MultiCastHost = "" ; private UdpClient udpClient = null ; public UdpClientManager( int localPort, string MultiCastHost) { if (localPort < 0 || localPort > 65535) throw new ArgumentOutOfRangeException( "localPort is out of range" ); if ( string .IsNullOrEmpty(MultiCastHost)) throw new ArgumentNullException( "message cant not null" ); this .localPort = localPort; this .MultiCastHost = MultiCastHost; } public void Start() { while ( true ) { try { udpClient = new UdpClient(localPort, AddressFamily.InterNetwork); //指定本地监听port udpClient.JoinMulticastGroup(IPAddress.Parse(MultiCastHost)); ReceiveMessage(); break ; } catch (Exception) { Thread.Sleep(100); } } } private async void ReceiveMessage() { while ( true ) { if (udpClient == null ) return ; try { UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer); if (recvMessageEvent != null ) recvMessageEvent(message); } catch (Exception ex) { } } } public async void SendMessageByMulticast( string message) { if ( string .IsNullOrEmpty(message)) throw new ArgumentNullException( "message cant not null" ); if (udpClient == null ) throw new ArgumentNullException( "udpClient cant not null" ); byte [] buffer = Encoding.UTF8.GetBytes(message); int len = 0; for ( int i = 0; i < 3; i++) { try { len = await udpClient.SendAsync(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(MultiCastHost), localPort)); } catch (Exception) { len = 0; } if (len <= 0) Thread.Sleep(100); else break ; } if (sendResultEvent != null ) sendResultEvent(len); } public void CloseUdpCliend() { if (udpClient == null ) throw new ArgumentNullException( "udpClient cant not null" ); try { udpClient.Client.Shutdown(SocketShutdown.Both); } catch (Exception) { } udpClient.Close(); udpClient = null ; } } |
分类:
c#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本