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


在此只做收藏被查,原文请访问:http://www.cnblogs.com/cgzwwy/archive/2009/12/10/1621389.html

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

代码
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的服务器

代码
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.

长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn