首先写个接受消息的客户端。这里偷了点懒,new UdpClient(11000)就是用Udp方式侦听11000端口,侦听任何发送到11000端口的消息都会接收到。
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
UdpClient udpClient
=
new
UdpClient(
11000
);
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0 );
Byte[] receiveBytes = udpClient.Receive( ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine( " This is the message you received " +
returnData.ToString());
Console.WriteLine( " This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
udpClient.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0 );
Byte[] receiveBytes = udpClient.Receive( ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine( " This is the message you received " +
returnData.ToString());
Console.WriteLine( " This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
udpClient.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
然后写个发Udp的服务器
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
UdpClient udpClient
=
new
UdpClient(
11001
);
try
{
udpClient.Connect(IPAddress.Parse( " 192.168.0.255 " ), 11000 );
Byte[] sendBytes = Encoding.ASCII.GetBytes( " Is anybody thereA? " );
udpClient.Send(sendBytes, sendBytes.Length);
udpClient.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
udpClient.Connect(IPAddress.Parse( " 192.168.0.255 " ), 11000 );
Byte[] sendBytes = Encoding.ASCII.GetBytes( " Is anybody thereA? " );
udpClient.Send(sendBytes, sendBytes.Length);
udpClient.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
其中192.168.0.255是你的内网广播地址,11000是客户端的端口。
广播地址是通过你的子网掩码获得的例如你的网关是192.168.0.1,掩码是255.255.255.0,那么你的广播地址就是192.168.0.255.