C# 广播通信
?? 單播(點對點) 通信,即網絡中單一的源節點發送封包到單一的上的節點。
??? 在廣播通信中, 網絡層提供了將封包從一個節點發送到所有其他節點的服務。
??? 利用廣播(broadcast) 可以將數據發送給本地子網上的每個機器。廣播的缺點是如果多個進程都發送廣播數據, 網絡就會阻塞。
1. 服務端
代碼 using System;using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace _5._2_廣播通信
{
class Program
{
staticvoid Main(string[] args)
{
Socket s =new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
byte[] buffer = Encoding.Unicode.GetBytes("Hello World");
IPEndPoint iep1 =new IPEndPoint(IPAddress.Broadcast, 4567);//255.255.255.255
int i =0;
while (true)
{
Console.WriteLine("正在進行廣播 {0}", i++.ToString());
s.SendTo(buffer, iep1);
Thread.Sleep(5000);
}
}
}
}
?? 對于UPD來說, 存在一個特定的廣播地址 - 255.255.255.255, 廣播數據都應該發送到這里。
? 廣播消息的目的IP地址是一種特殊IP地址,稱為廣播地址。
? 廣播地址由IP地址網絡前綴加上全1主機后綴組成,如:192.168.1.255 是 192.169.1.0 這個網絡的廣播地址;
? 130.168.255.255 是130.168.0.0 這個網絡的廣播地址。
? 向全部為1的IP地址(255.255.255.255)發送消息的話,那么理論上全世界所有的聯網的計算機都能收得到了。
? 但實際上不是這樣的,一般路由器上設置拋棄這樣的包,只在本地網內廣播,所以效果和向本地網的廣播地址發送消息是一樣的。
? 進行廣播通信, 必須打開廣播選項 SO_BROADCAST
2. 客戶端
代碼 using System;using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace Client
{
class Program
{
staticvoid Main(string[] args)
{
Socket m_s =new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep =new IPEndPoint(IPAddress.Any, 4567);
EndPoint ep = (EndPoint)iep;
m_s.Bind(iep);
byte[] buffer =newbyte[1204];
while (true)
{
int revc = m_s.ReceiveFrom(buffer, ref ep);
if (revc >0)
{
string data = Encoding.Unicode.GetString(buffer, 0, revc);
Console.WriteLine(data);
}
}
}
}
}
3. 效果
?
轉載于:https://www.cnblogs.com/LinFx/archive/2010/07/08/2123680.html
總結
- 上一篇: Console.WriteLine在以W
- 下一篇: 关于医学院网络中心成立工作室的设想