C# 广播通信
?? 單播(點(diǎn)對點(diǎn)) 通信,即網(wǎng)絡(luò)中單一的源節(jié)點(diǎn)發(fā)送封包到單一的上的節(jié)點(diǎn)。
??? 在廣播通信中, 網(wǎng)絡(luò)層提供了將封包從一個節(jié)點(diǎn)發(fā)送到所有其他節(jié)點(diǎn)的服務(wù)。
??? 利用廣播(broadcast) 可以將數(shù)據(jù)發(fā)送給本地子網(wǎng)上的每個機(jī)器。廣播的缺點(diǎn)是如果多個進(jìn)程都發(fā)送廣播數(shù)據(jù), 網(wǎng)絡(luò)就會阻塞。
1. 服務(wù)端
代碼 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("正在進(jìn)行廣播 {0}", i++.ToString());
s.SendTo(buffer, iep1);
Thread.Sleep(5000);
}
}
}
}
?? 對于UPD來說, 存在一個特定的廣播地址 - 255.255.255.255, 廣播數(shù)據(jù)都應(yīng)該發(fā)送到這里。
? 廣播消息的目的IP地址是一種特殊IP地址,稱為廣播地址。
? 廣播地址由IP地址網(wǎng)絡(luò)前綴加上全1主機(jī)后綴組成,如:192.168.1.255 是 192.169.1.0 這個網(wǎng)絡(luò)的廣播地址;
? 130.168.255.255 是130.168.0.0 這個網(wǎng)絡(luò)的廣播地址。
? 向全部為1的IP地址(255.255.255.255)發(fā)送消息的話,那么理論上全世界所有的聯(lián)網(wǎng)的計算機(jī)都能收得到了。
? 但實(shí)際上不是這樣的,一般路由器上設(shè)置拋棄這樣的包,只在本地網(wǎng)內(nèi)廣播,所以效果和向本地網(wǎng)的廣播地址發(fā)送消息是一樣的。
? 進(jìn)行廣播通信, 必須打開廣播選項(xiàng) 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. 效果
?
轉(zhuǎn)載于:https://www.cnblogs.com/LinFx/archive/2010/07/08/2123680.html
總結(jié)
- 上一篇: Console.WriteLine在以W
- 下一篇: c# winform程序调用托管dll(