C#使用UdpClient发送和接收UDP数据示例
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 //本段代码中需要新增加的命名空间 12 using System.Net.Sockets; 13 using System.Net; 14 using System.Threading; 15 16 namespace WinForm1 17 { 18 public partial class Form1 : Form 19 { 20 public Form1() 21 { 22 InitializeComponent(); 23 } 24 /// <summary> 25 /// 用于UDP发送的网络服务类 26 /// </summary> 27 private UdpClient udpcSend; 28 /// <summary> 29 /// 用于UDP接收的网络服务类 30 /// </summary> 31 private UdpClient udpcRecv; 32 33 /// <summary> 34 /// 按钮:发送数据 35 /// </summary> 36 /// <param name="sender"></param> 37 /// <param name="e"></param> 38 private void btnSend_Click(object sender, EventArgs e) 39 { 40 if (string.IsNullOrWhiteSpace(txtSendMssg.Text)) 41 { 42 MessageBox.Show("请先输入待发送内容"); 43 return; 44 } 45 46 // 匿名发送 47 //udpcSend = new UdpClient(0); // 自动分配本地IPv4地址 48 // 实名发送 49 IPEndPoint localIpep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345); // 本机IP,指定的端口号 50 udpcSend = new UdpClient(localIpep); 51 Thread thrSend = new Thread(SendMessage); 52 thrSend.Start(txtSendMssg.Text); 53 } 54 55 /// <summary> 56 /// 发送信息 57 /// </summary> 58 /// <param name="obj"></param> 59 private void SendMessage(object obj) 60 { 61 string message = (string)obj; 62 byte[] sendbytes = Encoding.Unicode.GetBytes(message); 63 IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8848); // 发送到的IP地址和端口号 64 udpcSend.Send(sendbytes, sendbytes.Length, remoteIpep); 65 udpcSend.Close(); 66 ResetTextBox(txtSendMssg); 67 } 68 69 /// <summary> 70 /// 开关:在监听UDP报文阶段为true,否则为false 71 /// </summary> 72 bool IsUdpcRecvStart = false; 73 /// <summary> 74 /// 线程:不断监听UDP报文 75 /// </summary> 76 Thread thrRecv; 77 78 /// <summary> 79 /// 按钮:接收数据开关 80 /// </summary> 81 /// <param name="sender"></param> 82 /// <param name="e"></param> 83 private void btnRecv_Click(object sender, EventArgs e) 84 { 85 if (!IsUdpcRecvStart) // 未监听的情况,开始监听 86 { 87 IPEndPoint localIpep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8848); // 本机IP和监听端口号 88 udpcRecv = new UdpClient(localIpep); 89 thrRecv = new Thread(ReceiveMessage); 90 thrRecv.Start(); 91 IsUdpcRecvStart = true; 92 ShowMessage(txtRecvMssg, "UDP监听器已成功启动"); 93 } 94 else // 正在监听的情况,终止监听 95 { 96 thrRecv.Abort(); // 必须先关闭这个线程,否则会异常 97 udpcRecv.Close(); 98 IsUdpcRecvStart = false; 99 ShowMessage(txtRecvMssg, "UDP监听器已成功关闭"); 100 } 101 } 102 103 /// <summary> 104 /// 接收数据 105 /// </summary> 106 /// <param name="obj"></param> 107 private void ReceiveMessage(object obj) 108 { 109 IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0); 110 while (true) 111 { 112 try 113 { 114 byte[] bytRecv = udpcRecv.Receive(ref remoteIpep); 115 string message = Encoding.Unicode.GetString(bytRecv, 0, bytRecv.Length); 116 ShowMessage(txtRecvMssg,string.Format("{0}[{1}]", remoteIpep, message)); 117 } 118 catch (Exception ex) 119 { 120 ShowMessage(txtRecvMssg, ex.Message); 121 break; 122 } 123 } 124 } 125 126 // 向RichTextBox中添加文本 127 delegate void ShowMessageDelegate(RichTextBox txtbox, string message); 128 private void ShowMessage(RichTextBox txtbox, string message) 129 { 130 if (txtbox.InvokeRequired) 131 { 132 ShowMessageDelegate showMessageDelegate = ShowMessage; 133 txtbox.Invoke(showMessageDelegate, new object[] { txtbox, message }); 134 } 135 else 136 { 137 txtbox.Text += message + "\r\n"; 138 } 139 } 140 141 // 清空指定RichTextBox中的文本 142 delegate void ResetTextBoxDelegate(RichTextBox txtbox); 143 private void ResetTextBox(RichTextBox txtbox) 144 { 145 if (txtbox.InvokeRequired) 146 { 147 ResetTextBoxDelegate resetTextBoxDelegate = ResetTextBox; 148 txtbox.Invoke(resetTextBoxDelegate, new object[] { txtbox }); 149 } 150 else 151 { 152 txtbox.Text = ""; 153 } 154 } 155 156 /// <summary> 157 /// 关闭程序,强制退出 158 /// </summary> 159 /// <param name="sender"></param> 160 /// <param name="e"></param> 161 private void Form1_FormClosing(object sender, FormClosingEventArgs e) 162 { 163 Environment.Exit(0); 164 } 165 } 166 }