[csharp] view plaincopy print?
代碼?? ?? Code?highlighting?produced?by?Actipro?CodeHighlighter?(freeware)http:?? ????{?? ?? ????????static ?bool ?connecting?=?true ;?? ????????static ?void ?Main()?? ????????{?? ????????????Received();?? ????????????while ?(connecting)?? ????????????{?? ????????????????string ?content?=?Console.ReadLine();?? ????????????????if ?(content.Length?>?0)?? ????????????????{?? ????????????????????if ?(string .Compare(content,?"<Stop>" ,?true )?==?0)?? ????????????????????{?? ????????????????????????Console.WriteLine("關閉..." );?? ????????????????????????connecting?=?false ;?? ????????????????????}?? ????????????????????else ?? ????????????????????{?? ????????????????????????Send(content);?? ????????????????????}?? ????????????????}?? ????????????}?? ????????????Console.ReadKey();?? ????????}?? ?? ????????public ?static ?void ?Send(string ?content)?? ????????{?? ????????????Socket?sock?=?new ?Socket(AddressFamily.InterNetwork,?SocketType.Dgram,?ProtocolType.Udp);?? ?????????????? ????????????IPEndPoint?iep2?=?new ?IPEndPoint(IPAddress.Parse("192.168.100.255" ),?9050);?? ????????????? ????????????byte []?data?=?Encoding.ASCII.GetBytes(content);?? ????????????sock.SetSocketOption(SocketOptionLevel.Socket,?? ????????????SocketOptionName.Broadcast,?1);?? ?????????????? ????????????sock.SendTo(data,?iep2);?? ????????????sock.Close();?? ????????}?? ?? ????????public ?static ?void ?Received()?? ????????{?? ????????????ThreadPool.QueueUserWorkItem((x)?=>?? ????????????{?? ????????????????Socket?sock?=?new ?Socket(AddressFamily.InterNetwork,?SocketType.Dgram,?ProtocolType.Udp);?? ????????????????IPEndPoint?iep?=?new ?IPEndPoint(IPAddress.Any,?9050);?? ????????????????sock.Bind(iep);?? ????????????????EndPoint?ep?=?(EndPoint)iep;?? ?? ????????????????byte []?data;?? ????????????????int ?recv;?? ????????????????string ?stringData;?? ????????????????Console.WriteLine("接聽開啟..." );?? ????????????????while ?(connecting)?? ????????????????{?? ????????????????????data?=?new ?byte [1024];?? ????????????????????recv?=?sock.ReceiveFrom(data,?ref ?ep);?? ????????????????????stringData?=?Encoding.ASCII.GetString(data,?0,?recv);?? ????????????????????Console.WriteLine("信息:?{0}?來自:?{1}" ,?stringData,?ep.ToString());?? ????????????????}?? ????????????????Console.WriteLine("接聽關閉..." );?? ????????????????sock.Close();?? ????????????});?? ????????}?? ?? ????}?? 代碼Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> class Program{static bool connecting = true;static void Main(){Received();while (connecting){string content = Console.ReadLine();if (content.Length > 0){if (string.Compare(content, "<Stop>", true) == 0){Console.WriteLine("關閉...");connecting = false;}else{Send(content);}}}Console.ReadKey();}public static void Send(string content){Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);//255.255.255.255 IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.100.255"), 9050);// string hostname = Dns.GetHostName();byte[] data = Encoding.ASCII.GetBytes(content);sock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast, 1);//sock.SendTo(data, iep1);sock.SendTo(data, iep2);sock.Close();}public static void Received(){ThreadPool.QueueUserWorkItem((x) =>{Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);sock.Bind(iep);EndPoint ep = (EndPoint)iep;byte[] data;int recv;string stringData;Console.WriteLine("接聽開啟...");while (connecting){data = new byte[1024];recv = sock.ReceiveFrom(data, ref ep);stringData = Encoding.ASCII.GetString(data, 0, recv);Console.WriteLine("信息: {0} 來自: {1}", stringData, ep.ToString());}Console.WriteLine("接聽關閉...");sock.Close();});}}
?
從原理角度考慮,廣播和單向定點發送沒什么區別,獻上一段小代碼(來自msdn),基本很詳細的說了如何廣播式發送udp數據包:
?
[csharp] view plaincopy print?
using ???System;???????using ???System.Net;????? ??using ???System.Net.Sockets;????? ??using ???System.Text;????? ?????? ??public ???class ???UDPMulticastSender???{????? ?????? ??????????private ???static ???IPAddress???GroupAddress???=??????? ??????????????????IPAddress.Parse("224.168.100.2" );????? ??????????private ???static ???int ???GroupPort???=???11000;????? ?????????????? ??????????private ???static ???void ???Send(???String???message)???{????? ??????????????????UdpClient???sender???=???new ???UdpClient();????? ??????????????????IPEndPoint???groupEP???=???new ???IPEndPoint(GroupAddress,GroupPort);????? ?????? ??????????????????try ???{????? ??????????????????????????Console.WriteLine("Sending???datagram???:???{0}" ,???message);????? ??????????????????????????byte []???bytes???=???Encoding.ASCII.GetBytes(message);????? ?????? ??????????????????????????sender.Send(bytes,???bytes.Length,???groupEP);????? ?????????????????????????????? ??????????????????????????sender.Close();????? ?????????????????????????????? ??????????????????}???catch ???(Exception???e)???{????? ??????????????????????????Console.WriteLine(e.ToString());????? ??????????????????}????? ?????????????????????? ??????????}????? ?????? ??????????public ???static ???int ???Main(String[]???args)???{????? ??????????????????Send(args[0]);????? ?????? ??????????????????return ???0;????? ??????????}??? using System; using System.Net; using System.Net.Sockets; using System.Text; public class UDPMulticastSender { private static IPAddress GroupAddress = IPAddress.Parse("224.168.100.2"); private static int GroupPort = 11000; private static void Send( String message) { UdpClient sender = new UdpClient(); IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort); try { Console.WriteLine("Sending datagram : {0}", message); byte[] bytes = Encoding.ASCII.GetBytes(message); sender.Send(bytes, bytes.Length, groupEP); sender.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } public static int Main(String[] args) { Send(args[0]); return 0; }
?單播(點對點) 通信,即網絡中單一的源節點發送封包到單一的上的節點。
??? 在廣播通信中, 網絡層提供了將封包從一個節點發送到所有其他節點的服務。
??? 利用廣播(broadcast) 可以將數據發送給本地子網上的每個機器。廣播的缺點是如果多個進程都發送廣播數據, 網絡就會阻塞。
1. 服務端
[csharp] view plaincopy print?
using ?System;??using ?System.Collections.Generic;??using ?System.Text;??using ?System.Net.Sockets;??using ?System.Net;??using ?System.Threading;???? namespace ?_5._2_廣播通信??{?? ????class ?Program?? ????{?? ????????static ?void ?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);?? ?? ????????????int ?i?=?0;?? ????????????while ?(true )?? ????????????{?? ????????????????Console.WriteLine("正在進行廣播?{0}" ,?i++.ToString());?? ????????????????s.SendTo(buffer,?iep1);?? ????????????????Thread.Sleep(5000);?? ????????????}?? ????????}?? ????}?? }?? using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;namespace _5._2_廣播通信
{class Program{static void 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.255int 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. 客戶端
[csharp] view plaincopy print?
using ?System;??using ?System.Collections.Generic;??using ?System.Text;??using ?System.Net.Sockets;??using ?System.Net;???? namespace ?Client??{?? class ?Program???{?? static ?void ?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?=?new ?byte [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);?? ?}?? ?}?? ?}?? ?}?? }?? using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;namespace Client
{
class Program{
static void 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 = new byte[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. 效果
?
?
?C#實現局域網UDP廣播,這一塊設置到局域網,需要用到的主要命名空間是:System.NET和System.Net.Scoket:
接收端:
?????????? Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//初始化一個Scoket協議
??????????? IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9095);//初始化一個偵聽局域網內部所有IP和指定端口
??????????? EndPoint ep = (EndPoint)iep;
??????????? socket.Bind(iep);//綁定這個實例
??????????? while (true)
??????????????????
{ ?????????????? byte[] buffer = new byte[1024];//設置緩沖數據流 ???????????? socket.ReceiveFrom(buffer, ref ep);//接收數據,并確把數據設置到緩沖流里面 ?????????? ??????? Console.WriteLine(Encoding.Unicode.GetString(buffer2).TrimEnd('/u0000') + " " + DateTime.Now.ToString()); }
發送端:
??????????? Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//初始化一個Scoket實習,采用UDP傳輸
??????????? IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9095);//初始化一個發送廣播和指定端口的網絡端口實例
??????????? sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);//設置該scoket實例的發送形式
??????????? string request = "你好,TEST SEND!";//初始化需要發送而的發送數據
??????????? byte[] buffer = Encoding.Unicode.GetBytes(request);
??????????? sock.SendTo(buffer, iep);
??????????? sock.Close();
總結
以上是生活随笔 為你收集整理的C#实现 UDP简单广播 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。