一、核心理论考点(UdpClient 专属)
1.1 Udp 协议核心特性
-
无连接、不可靠、面向数据报传输,无需三次握手
-
无需监听、无需接受连接,直接收发数据
-
点对点自由通信,没有严格服务端/客户端区分
1.2 UdpClient 与原生 Socket(UDP) 区别(考试高频)
-
原生Socket:需要手动创建 Dgram 套接字、Bind、ReceiveFrom、SendTo
-
UdpClient 封装版:简化写法,内置绑定、收发方法,代码更简洁,适合快速开发UDP通信
-
核心方法:
Receive()、Send()
1.3 固定端口通信原理
UDP通信必须保证:一端绑定本机端口,发送数据填写对方IP+端口,双向互为收发。
二、UDP单播核心理论(必考简答题)
2.1 单播定义
UDP单播 :一对一精准通信,数据只能发送给指定唯一IP+端口的设备,点对点专属数据交互。
2.2 核心特性
-
无连接、面向数据报,无需三次握手,通信效率高
-
通信双方必须端口互不冲突、互相指定对方终端
-
发送必须指定目标IPEndPoint,不能全网群发
-
两端均需绑定本地端口,同时具备收发能力(UDP对等通信)
2.3 单播 VS 广播(必背对比)
-
单播:一对一,指定唯一目标终端,数据私密性高
-
广播:一对多,目标255.255.255.255,局域网所有同端口设备接收
三、版本一:固定双端UDP通信(A端源码+解析)
3.1 项目说明
A端固定绑定:192.168.219.9:9999,默认发送目标:B端 192.168.219.9:9998
3.2 完整可运行代码
cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _1UDPA端
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
UdpClient udpA;
IPEndPoint endpointB;
CancellationTokenSource cts;
private void button1_Click(object sender, EventArgs e)
{
try
{
if (button1.Text == "启动")
{
// A端绑定本机固定IP和端口
udpA = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.219.9"), 9999));
button1.Text = "停止";
// 指定B端通信终端
endpointB = new IPEndPoint(IPAddress.Parse("192.168.219.9"), 9998);
cts = new CancellationTokenSource();
// 异步循环接收数据
Task.Run(() =>
{
while (!cts.IsCancellationRequested)
{
if (udpA.Available == 0)
{
continue;
}
// 接收对方数据,自动刷新发送方终端
byte[] buffer = udpA.Receive(ref endpointB);
Invoke(new Action(() =>
{
string msg = Encoding.UTF8.GetString(buffer);
richTextBox1.Text += $"{endpointB}:{msg}{Environment.NewLine}";
}));
}
}, cts.Token);
}
else
{
// 安全释放资源
cts?.Cancel();
udpA?.Close();
udpA = null;
endpointB = null;
button1.Text = "启动";
}
}
catch (Exception)
{
Console.WriteLine("");
}
}
// 主动发送数据到B端
private void button2_Click(object sender, EventArgs e)
{
byte[] bs = Encoding.UTF8.GetBytes(textBox1.Text);
udpA.Send(bs, bs.Length, endpointB);
}
}
}
四、版本二:固定双端UDP通信(B端源码+解析)
4.1 项目说明
B端固定绑定:192.168.219.9:9998,默认发送目标:A端 192.168.219.9:9999,与A端完美双向通信
4.2 完整可运行代码
cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _2UDPB端
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
UdpClient udpB;
IPEndPoint endPointA;
CancellationTokenSource cts;
private void button1_Click(object sender, EventArgs e)
{
try
{
if (button1.Text == "启动")
{
// B端绑定本机固定端口
udpB = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.219.9"), 9998));
button1.Text = "停止";
// 指定A端通信终端
endPointA = new IPEndPoint(IPAddress.Parse("192.168.219.9"), 9999);
cts = new CancellationTokenSource();
// 异步接收消息
Task.Run(() =>
{
while (!cts.IsCancellationRequested)
{
if (udpB.Available == 0)
{
continue;
}
byte[] buffer = udpB.Receive(ref endPointA);
Invoke(new Action(() =>
{
string msg = Encoding.UTF8.GetString(buffer);
richTextBox1.Text += $"{endPointA}:{msg}{Environment.NewLine}";
}));
}
}, cts.Token);
}
else
{
cts?.Cancel();
udpB?.Close();
udpB = null;
endPointA = null;
button1.Text = "启动";
}
}
catch (Exception)
{
Console.WriteLine("");
}
}
// B端发送数据到A端
private void button2_Click(object sender, EventArgs e)
{
byte[] bs = Encoding.UTF8.GetBytes(textBox1.Text);
udpB.Send(bs, bs.Length, endPointA);
}
}
}
五、版本三:通用自定义UDP端(万能通信端)
5.1 项目优势(考试重点)
-
手动自定义本机IP、本机绑定端口
-
手动输入对方IP端口,可与任意UDP设备通信
-
通用性最强,适配所有UDP点对点通信场景
5.2 完整万能UDP客户端代码
cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _3UDP通用端
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
CancellationTokenSource cts;
UdpClient udpClient;
private void button1_Click(object sender, EventArgs e)
{
try
{
if (button1.Text == "启动")
{
// 自定义本机绑定IP和端口
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));
udpClient = new UdpClient(localEndPoint);
button1.Text = "停止";
cts = new CancellationTokenSource();
// 异步循环接收所有终端发来的数据
Task.Run(() =>
{
while (!cts.IsCancellationRequested)
{
if (udpClient.Available == 0) continue;
// 任意终端接收
IPEndPoint end = new IPEndPoint(IPAddress.Any, 0);
byte[] buffer = udpClient.Receive(ref end);
Invoke(new Action(() =>
{
string msg = Encoding.UTF8.GetString(buffer);
richTextBox1.Text += $"{end}:{msg}{Environment.NewLine}";
}));
}
}, cts.Token);
}
else
{
// 关闭释放
cts?.Cancel();
udpClient?.Close();
udpClient = null;
button1.Text = "启动";
}
}
catch (Exception)
{
throw;
}
}
// 自定义目标IP端口发送消息
private void button2_Click(object sender, EventArgs e)
{
byte[] bs = Encoding.UTF8.GetBytes(textBox3.Text);
// 拆分输入的 IP:Port
string ip = textBox4.Text.Split(':')[0];
string port = textBox4.Text.Split(':')[1];
udpClient.Send(bs, bs.Length, new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)));
}
}
}
六、三套代码核心考点对比(必背)
| 版本 | 绑定方式 | 发送目标 | 适用场景 |
|---|---|---|---|
| 固定A端 | 固定9999端口 | 固定发往9998 | 双端固定聊天室 |
| 固定B端 | 固定9998端口 | 固定发往9999 | 双端固定聊天室 |
| 通用端 | 自定义IP端口 | 自定义任意终端 | 万能UDP调试、任意设备通信 |
七、UdpClient 高频易错点(考试扣分点)
-
端口冲突:同一台电脑同一端口不能重复绑定
-
跨线程UI报错:子线程刷新文本框必须使用 Invoke
-
资源泄漏:关闭必须 Close()、置空、取消线程令牌
-
UDP无连接:对方离线不会报错,静默丢包
-
Receive(ref endPoint):ref 参数会自动更新发送方终端地址
八、简答题满分模版
UdpClient是.NET封装的UDP通信工具类,基于无连接数据报协议实现点对点通信。无需建立连接、无需监听等待,只需绑定本机IP端口即可收发数据。通过异步Task循环接收远端数据,使用Invoke完成跨线程UI更新,支持固定双端点对点通信与自定义万能UDP通信,实现双向消息透传,通信简洁高效,适用于轻量快速数据交互场景。