创建 UdpClient
注意:在 .net framework 4.6 中,创建对象时,必须使用下面方式:
// 使用本机的 127.0.0.1 ip,10000端口号
IPEndPoint meEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10000);
UdpClient listener = new UdpClient(meEP);
不能使用下面方式创建对象,接收不到数据:
UdpClient listener = new UdpClient("127.0.0.1",10000);
发送数据
发送给远端 ip、port
IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(remoteIP, 10000);
Byte[] sendBytes = Encoding.Default.GetBytes("(" + DateTime.Now.ToLongTimeString() + "),测试数据");
client.Send(sendBytes, sendBytes.Length, remoteEP);
接收数据
需要指定 IPEndPoint
对象,接收任意 ip、port 发送的数据
// IPAddress.Any 的本质是 0.0.0.0
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0);
byte[] bytes = listener.Receive(ref groupEP);
接收指定 ip、port 发送的数据
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10000);
byte[] bytes = listener.Receive(ref groupEP);
服务器端-例子
接收数据,并弹出窗口
// 创建 UdpClient时,必须使用 IPEndPoint,不能用字符串,否则接收不到数据
IPEndPoint meEP = new IPEndPoint(IPAddress.Parse(ip), port);
UdpClient listener = new UdpClient(meEP);
//可以接收任意ip、任意端口的数据包
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0);
// 将 UdpClient 添加到多播组; IPAddress.Parse将IP地址字符串转换为IPAddress 实例
//listener.JoinMulticastGroup(GroupAddress);
Task t = new Task(() =>
{
while (!done)
{
try
{
//调用UdpClient对象的Receive方法获得从远程主机返回的UDP数据报
byte[] bytes = listener.Receive(ref groupEP);
//将获得的UDP数据报转换为字符串形式
string str = Encoding.Default.GetString(bytes);
MethodInvoker mi = new MethodInvoker(() =>
{
if(GlobalVaribal.form2 == null || GlobalVaribal.form2.IsDisposed)
{
GlobalVaribal.form2 = new Form2();
GlobalVaribal.form2.Show();
}
GlobalVaribal.form2.textBox1.Text= str;
});
if (GlobalVaribal.form2 == null || GlobalVaribal.form2.IsDisposed)
{
GlobalVaribal.form2 = new Form2();
}
GlobalVaribal.form1.Invoke((MethodInvoker)delegate () {
if (GlobalVaribal.form2 != null && !GlobalVaribal.form2.IsDisposed)
{
GlobalVaribal.form2.Show();
GlobalVaribal.form2.BeginInvoke(mi);
}
});
}
catch (Exception e)
{
MessageBox.Show(e.Message);//错误提示
}
}
listener.Close();
});
t.Start();
客户端-例子
//IPEndPoint meIP = new IPEndPoint(IPAddress.Parse(ip), port);
UdpClient client = new UdpClient();//定义本地IP地址和端口号
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ip), port);//定义目标地址和端口号
Task task = new Task(() => {
while (true)
{
try
{
Byte[] sendBytes = Encoding.Default.GetBytes("(" + DateTime.Now.ToLongTimeString() + "),测试数据");
client.Send(sendBytes, sendBytes.Length, remoteEP);//将UDP数据报发送到位于指定远程终结点的主机
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);//错误提示
}
}
});
task.Start();