c# UDP 通信协议
·
TCPUDP 网络调试助手
一款 Windows 轻量工具,专门调试 TCP、UDP 网络通信,做工控、机器视觉、Socket 上位机开发必备,不用自己写服务端 / 客户端代码,一键收发报文测试
在微软应用商店下载即可

工作模式
- TCP 客户端 主动连接设备 / 程序 IP + 端口。 用途:连接工业相机、PLC、机器人、自己写的 C# 服务端,下发指令、接收返回数据。
- TCP 服务端 本机开启端口监听,等待设备主动接入,支持多客户端同时连接。 比如你的视觉程序起 TCP 服务,用调试助手模拟相机发图像数据。
- UDP 客户端 无连接,直接向指定 IP 端口发包,不用握手。 适配传感器、摄像头 UDP 上报、广播设备。
- UDP 服务端 监听本机端口,接收任意设备发来的 UDP 数据包。
c# 程序
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace test006
{
internal class Program
{
public static void Main(string[] args)
{
new UdpSender().Send();
}
}
public class UdpSender
{
public void Send()
{
// 创建 UdpClient 实例,绑定本地端口 10086(发送端端口)
var client = new UdpClient(10011);
// 循环读取用户输入并发送
while (true)
{
// 提示用户输入要发送的消息
Console.WriteLine("请输入要发送的消息:");
var msg = Console.ReadLine();
// 输入 exit 时退出循环
if (msg == "exit")
{
Console.WriteLine("退出");
break;
}
// 将字符串消息转换为 UTF-8 编码的字节数组
var data = Encoding.UTF8.GetBytes(msg);
// 构造接收端的 IP 地址和端口号(127.0.0.1:10010)
var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10010);
// 通过 UDP 协议将数据发送到指定的接收端
client.Send(data, data.Length, endPoint);
Console.WriteLine("发送成功");
// 休眠 1 秒,避免发送过快
Thread.Sleep(1000);
}
}
}
}
UDP 发送端程序 - 原理思维导图

数据流传图

发送端

ip 端口 要跟代码保持一直
接收端采用 TCPUDP 网络调试助手

接收端
UDP 接收端
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace TestReceive
{
internal class Program
{
public static void Main(string[] args)
{
Console.Title = "TestReceive";
new Program().Receive();
}
// UDP接收数据
public void Receive()
{
// 远程终端点,用于存储发送方的IP和端口信息
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
// 创建UdpClient并绑定本地端口10012,using确保资源释放
using (UdpClient client = new UdpClient(10012))
{
while (true)
{
// 阻塞等待并接收数据,同时获取发送方地址
byte[] data = client.Receive(ref remoteEndPoint);
// 将字节数组解码为UTF8字符串
string message = Encoding.UTF8.GetString(data);
// 收到exit则退出循环
if (message == "exit")
{
Console.WriteLine("已退出");
break;
}
// 输出接收到的数据及发送方地址
Console.WriteLine($"接收数据: {message} (来自 {remoteEndPoint})");
}
}
}
catch (Exception ex)
{
// 捕获异常(如端口被占用、网络中断等)
Console.WriteLine($"异常: {ex.Message}");
}
}
}
}

ip 端口 要跟代码保持一直
发送端采用 TCPUDP 网络调试助手

更多推荐


所有评论(0)