1、软件UI测试界面
文章图片
2、创建Config.ini配置文件
[系统参数]
本地UDP地址=192.168.124.4
本地UDP端口=7788
目标控制器IP地址=192.168.124.255
目标控制器端口号=6666
文章图片
3、创建全局变量
IniFile ini = new IniFile("./Config.ini");
bool isUdpConnected = false;
static Socket client;
Thread threadRecv;
string recv;
string LocalIp = "192.168.1.25";
int LocalPort = 1000;
string TargetIp = "192.168.1.255";
int TargetPort = 10000;
4、添加UdpForm_Load事件程序
private void UdpForm_Load(object sender, EventArgs e)
{
try
{LocalIp = ini.IniReadValue("系统参数", "本地UDP地址");
LocalPort = int.Parse(ini.IniReadValue("系统参数", "本地UDP端口"));
TargetIp = ini.IniReadValue("系统参数", "目标控制器IP地址");
TargetPort = int.Parse(ini.IniReadValue("系统参数", "目标控制器端口号"));
txtLocalIp.Text = LocalIp;
txtLocalPort.Text = LocalPort.ToString();
txtTargetIp.Text = TargetIp;
txtTargetPort.Text = TargetPort.ToString();
client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.Bind(new IPEndPoint(IPAddress.Parse(LocalIp), LocalPort));
Thread.Sleep(50);
txtUdpState.Text = "本地Udp创建成功";
isUdpConnected = true;
}
catch
{
txtUdpState.Text = "本地Udp创建失败";
isUdpConnected = false;
}threadRecv = new Thread(ReciveMsg);
threadRecv.Start();
timer1.Start();
}
5、创建线程ReciveMsg()处理函数
///
/// 接收发送给本机ip对应端口号的数据报
///
void ReciveMsg()
{
while (true)
{
if(isUdpConnected)
{EndPoint point = new IPEndPoint(IPAddress.Any, 0);
//用来保存发送方的ip和端口号
byte[] buffer = new byte[1024];
int length = client.ReceiveFrom(buffer, ref point);
//接收数据报
if(length>0)
{
//显示对方ip地址和端口号
string fromIp = point.ToString();
recv += fromIp;
recv += "\r\n";
//显示发送时间
string sTime = DateTime.Now.ToString();
recv += sTime;
recv += ":";
}recv += Encoding.UTF8.GetString(buffer, 0, length);
recv += "\r\n";
/*
EndPoint point = new IPEndPoint(IPAddress.Any, 0);
//用来保存发送方的ip和端口号
byte[] buffer = new byte[1024];
int length = client.ReceiveFrom(buffer, ref point);
//接收数据报
recv += Encoding.UTF8.GetString(buffer, 0, length);
recv += "\r\n";
//txtReciv.Text += recv;
*/
}}
}
6、添加btnSend_Click按钮事件程序
private void btnSend_Click(object sender, EventArgs e)
{
try
{
UdpSend(txtSend.Text, TargetIp, TargetPort);
}
catch
{}
}
7、封装UdpSend方法
///
/// 本地Udp对外单播
///
///
/// 【C#|C# Udp测试工具开发】
///
private void UdpSend(string strSend, string ip, int port)
{
try
{
if (isUdpConnected)
{
string targetIp = ip;
//int targetPort = int.Parse(port);
EndPoint point = new IPEndPoint(IPAddress.Parse(targetIp), port);
string msg = strSend;
client.SendTo(Encoding.UTF8.GetBytes(msg), point);
}
}
catch { }}
8、关闭程序,关闭创建的所有线程
private void UdpForm_FormClosing(object sender, FormClosingEventArgs e)
{
System.Environment.Exit(0);
//强制关闭所有线程
}
下载连接
https://download.csdn.net/download/panjinliang066333/85567657
推荐阅读
- C#|C#数据库教程2-ADO.NET常用SQL语句
- ADO.NET|C# Access数据库使用
- Java|微服务入门基础
- 网络|ACL(访问控制列表(Access Control List))
- IT尖端技术|基于高端全闪存存储在医院中的应用与探索
- 网络技术|华为交换机Hybrid接口原理及应用
- 华为认证好考吗
- 路由进阶与安全|第二章OSPF路由协议
- 数据中心技术|数据中心——Vxlan基本概念2