示例C#利用UdpClient发送广播消息

本文介绍了如何使用C#实现UDP客户端与服务器之间的通信。包括创建UDP客户端接收消息及UDP服务器发送消息的具体代码示例,并解释了如何指定广播地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先写个接受消息的客户端。这里偷了点懒,new UdpClient(11000)就是用Udp方式侦听11000端口,侦听任何发送到11000端口的消息都会接收到。

 

ContractedBlock.gifExpandedBlockStart.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());
}

 

 

 

然后写个发Udp的服务器

 

ContractedBlock.gifExpandedBlockStart.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());
}

 

 

 

其中192.168.0.255是你的内网广播地址,11000是客户端的端口。

广播地址是通过你的子网掩码获得的例如你的网关是192.168.0.1,掩码是255.255.255.0,那么你的广播地址就是192.168.0.255.

转载于:https://www.cnblogs.com/cgzwwy/archive/2009/12/10/1621389.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值