UdpClient 类使用字节数组保存 UDP 数据文报。使用 Send 方法向网络发送数据,使用 Receive 方法接收传入的数据文报。
UdpClient 类提供了一些简单的方法,用于在阻止同步模式下发送和接收无连接 UDP 数据报。因为 UDP 是无连接传输协议,所以不需要在发送和接收数据前建立远程主机连接。但您可以选择使用下面两种方法之一来建立默认远程主机:
使用远程主机名和端口号作为参数创建 UdpClient 类的实例。
创建 UdpClient 类的实例,然后调用 Connect 方法。
可以使用在 UdpClient 中提供的任何一种发送方法将数据发送到远程设备。使用 Receive 方法可以从远程主机接收数据。
UdpClient 方法还允许发送和接收多路广播数据报。使用 JoinMulticastGroup 方法可以将 UdpClient 预订给多路广播组。使用 DropMulticastGroup 方法可以从多路广播组中取消对 UdpClient 的预订。
简例:
作为服务端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace udpClient
{
class Program
{
static void Main(string[] args)
{
//创建udpClient 绑定Ip跟端口号,,
UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.1.11"), 3355));
Console.WriteLine("创建UdpClient服务端");
while (true)
{
//接收数据
IPEndPoint point = new IPEndPoint(IPAddress.Any, 0);
//通过point确定数据来自哪个ip的端口号,返回值是一个字节数组,
byte[] data = udpClient.Receive(ref point);
string message = Encoding.UTF8.GetString(data);
Console.WriteLine("收到了消息:" + message);
}
udpClient.Close();
Console.ReadKey();
}
}
}
作为客户端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace _004_udpClient
{
class Program
{
static void Main(string[] args)
{
//创建UdpClient 绑定的端口号
UdpClient udpclient = new UdpClient();
Console.WriteLine("创建UdpClient客户端");
while (true)
{
string message = Console.ReadLine();
//将字符串转为数组
byte[] data = Encoding.UTF8.GetBytes(message);
//发送数据
int length = udpclient.Send(data, data.Length, new IPEndPoint(IPAddress.Parse("192.168.1.11"), 3355));
}
udpclient.Close();
Console.ReadKey();
}
}
}