C#使用UdpClient类进行简单通信的实例
UdpClient类提供了一些简单的方法,用于在阻止同步模式下发送和接收无连接UDP数据报。因为UDP是无连接传输协议,所以不需要在发送和接收数据前建立远程主机连接。但您可以选择使用下面两种方法之一来建立默认远程主机:
- 使用远程主机名和端口号作为参数创建UdpClient类的实例。
- 创建UdpClient类的实例,然后调用Connect方法。
可以使用在UdpClient中提供的任何一种发送方法将数据发送到远程设备。使用Receive方法可以从远程主机接收数据。
UdpClient方法还允许发送和接收多路广播数据报。使用JoinMulticastGroup方法可以将UdpClient预订给多路广播组。使用DropMulticastGroup方法可以从多路广播组中取消对UdpClient的预订。
///<summary>
///客户端
///</summary>
classUDPSender
{
staticvoidMain(string[]args)
{
//创建一个UdpClient对象,0表示系统自动分配发送端口
//(若同时在本机运行服务端和客户端,则服务端接收和客户端发送需要使用不同端口,否则两个程序使用同一端口将引发冲突)
UdpClientudpSender=newUdpClient(0);
//连接到服务端并指定接收端口
udpSender.Connect("localhost",11000);
//连接到子网广播地址并指定接收端口
//udpSender.Connect("192.168.1.255",11000);
//(在使用TCP/IP协议的网络中,主机标识段全为1的IP地址为广播地址,广播地址传送给主机标识段所涉及的所有计算机。
//例如,对于192.168.1.0(255.255.255.0)网段,其广播地址为192.168.1.255(255的2进制即为11111111),
//当发出目的地址为192.168.1.255时,它将分发给该网段上的所有计算机。)
//把消息转换成字节流发送到服务端
byte[]sendBytes=Encoding.ASCII.GetBytes("Isanybodythere?");
udpSender.Send(sendBytes,sendBytes.Length);
//关闭链接
udpSender.Close();
}
}
///<summary>
///服务端
///</summary>
classUDPReceive
{
staticvoidMain(string[]args)
{
//创建一个UdpClient对象,11000为接收端口
UdpClientudpReceive=newUdpClient(11000);
//设置远程主机,(IPAddress.Any,0)代表接收所有IP所有端口发送的数据
IPEndPointremoteIpEndPoint=newIPEndPoint(IPAddress.Any,0);//或IPEndPointremoteIpEndPoint=null;
//监听数据,接收到数据后,把数据转换成字符串并输出
byte[]receiveBytes=udpReceive.Receive(refremoteIpEndPoint);
stringreturnData=Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("Thisisthemessageyoureceived"+returnData.ToString());
Console.WriteLine("Thismessagewassentfrom"+remoteIpEndPoint.Address.ToString()+"ontheirportnumber"+remoteIpEndPoint.Port.ToString());
//关闭连接
udpReceive.Close();
}
}
备注:需要先运行服务端,再运行客户端。否则客户端在服务端运行之前就已经发出数据,则服务端不会接收到数据。
下面是使用UdpClient类进行多路广播组的简单例子,加入相同的广播组地址即可实现多播。多路广播地址的范围从224.0.0.0到239.255.255.255,服务端和客户端使用同一广播地址即可实现多播。
///<summary>
///多路广播组客户端
///</summary>
classMulticastGroupClient
{
staticvoidMain(string[]args)
{
//创建一个UdpClient对象,0表示系统自动分配发送端口
varclient=newUdpClient(0);
//将广播地址添加到多路广播组,生存期(路由器跳数)为10
varip=IPAddress.Parse("234.56.78.90");
client.JoinMulticastGroup(ip,10);
//定义终结点(服务端IP和接收端口),把消息转换成字节流后发送到服务端
varmulticast=newIPEndPoint(ip,7788);
byte[]bytes=Encoding.ASCII.GetBytes("Hellofrommulticast.");
client.Send(bytes,bytes.Length,multicast);
}
}
///<summary>
///多路广播组服务端
///</summary>
classMulticastGroupServer
{
staticvoidMain(string[]args)
{
//创建一个UdpClient对象,7788为接收端口
varclient=newUdpClient(7788);
//将广播地址添加到多路广播组,生存期(路由器跳数)为10
varip=IPAddress.Parse("234.56.78.90");
client.JoinMulticastGroup(ip,10);
//设置远程主机,(IPAddress.Any,0)代表接收所有IP所有端口发送的数据
varmulticast=newIPEndPoint(IPAddress.Any,0);//或IPEndPointmulticast=null;
//监听数据,接收到数据后,把数据转换成字符串并输出
byte[]bytes=client.Receive(refmulticast);
stringmsg=Encoding.ASCII.GetString(bytes);
Console.WriteLine(msg);
}
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!