C#实现 UDP简单广播

来源:互联网 发布:淘宝网上买酒怎么样 编辑:程序博客网 时间:2024/05/04 22:34


    [csharp] view plain copy
    print?
    1. 代码  
    2.   
    3. Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->    class Program  
    4.     {  
    5.   
    6.         static bool connecting = true;  
    7.         static void Main()  
    8.         {  
    9.             Received();  
    10.             while (connecting)  
    11.             {  
    12.                 string content = Console.ReadLine();  
    13.                 if (content.Length > 0)  
    14.                 {  
    15.                     if (string.Compare(content, "<Stop>"true) == 0)  
    16.                     {  
    17.                         Console.WriteLine("关闭...");  
    18.                         connecting = false;  
    19.                     }  
    20.                     else  
    21.                     {  
    22.                         Send(content);  
    23.                     }  
    24.                 }  
    25.             }  
    26.             Console.ReadKey();  
    27.         }  
    28.   
    29.         public static void Send(string content)  
    30.         {  
    31.             Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  
    32.             //IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);//255.255.255.255   
    33.             IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.100.255"), 9050);  
    34.            // string hostname = Dns.GetHostName();  
    35.             byte[] data = Encoding.ASCII.GetBytes(content);  
    36.             sock.SetSocketOption(SocketOptionLevel.Socket,  
    37.             SocketOptionName.Broadcast, 1);  
    38.             //sock.SendTo(data, iep1);  
    39.             sock.SendTo(data, iep2);  
    40.             sock.Close();  
    41.         }  
    42.   
    43.         public static void Received()  
    44.         {  
    45.             ThreadPool.QueueUserWorkItem((x) =>  
    46.             {  
    47.                 Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  
    48.                 IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);  
    49.                 sock.Bind(iep);  
    50.                 EndPoint ep = (EndPoint)iep;  
    51.   
    52.                 byte[] data;  
    53.                 int recv;  
    54.                 string stringData;  
    55.                 Console.WriteLine("接听开启...");  
    56.                 while (connecting)  
    57.                 {  
    58.                     data = new byte[1024];  
    59.                     recv = sock.ReceiveFrom(data, ref ep);  
    60.                     stringData = Encoding.ASCII.GetString(data, 0, recv);  
    61.                     Console.WriteLine("信息: {0} 来自: {1}", stringData, ep.ToString());  
    62.                 }  
    63.                 Console.WriteLine("接听关闭...");  
    64.                 sock.Close();  
    65.             });  
    66.         }  
    67.   
    68.     }  


     

    从原理角度考虑,广播和单向定点发送没什么区别,献上一段小代码(来自msdn),基本很详细的说了如何广播式发送udp数据包:

     

    [csharp] view plain copy
    print?
    1. using   System;     
    2.   using   System.Net;     
    3.   using   System.Net.Sockets;     
    4.   using   System.Text;     
    5.       
    6.   public   class   UDPMulticastSender   {     
    7.       
    8.           private   static   IPAddress   GroupAddress   =       
    9.                   IPAddress.Parse("224.168.100.2");     
    10.           private   static   int   GroupPort   =   11000;     
    11.               
    12.           private   static   void   Send(   String   message)   {     
    13.                   UdpClient   sender   =   new   UdpClient();     
    14.                   IPEndPoint   groupEP   =   new   IPEndPoint(GroupAddress,GroupPort);     
    15.       
    16.                   try   {     
    17.                           Console.WriteLine("Sending   datagram   :   {0}",   message);     
    18.                           byte[]   bytes   =   Encoding.ASCII.GetBytes(message);     
    19.       
    20.                           sender.Send(bytes,   bytes.Length,   groupEP);     
    21.                               
    22.                           sender.Close();     
    23.                               
    24.                   }   catch   (Exception   e)   {     
    25.                           Console.WriteLine(e.ToString());     
    26.                   }     
    27.                       
    28.           }     
    29.       
    30.           public   static   int   Main(String[]   args)   {     
    31.                   Send(args[0]);     
    32.       
    33.                   return   0;     
    34.           }   


     单播(点对点) 通信,即网络中单一的源节点发送封包到单一的上的节点。

        在广播通信中, 网络层提供了将封包从一个节点发送到所有其他节点的服务。

        利用广播(broadcast) 可以将数据发送给本地子网上的每个机器。广播的缺点是如果多个进程都发送广播数据, 网络就会阻塞。

    1. 服务端

    [csharp] view plain copy
    print?
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Text;  
    4. using System.Net.Sockets;  
    5. using System.Net;  
    6. using System.Threading;  
    7.   
    8. namespace _5._2_广播通信  
    9. {  
    10.     class Program  
    11.     {  
    12.         static void Main(string[] args)  
    13.         {  
    14.             Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  
    15.             s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);  
    16.   
    17.             byte[] buffer = Encoding.Unicode.GetBytes("Hello World");  
    18.             IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 4567);//255.255.255.255  
    19.   
    20.             int i = 0;  
    21.             while (true)  
    22.             {  
    23.                 Console.WriteLine("正在进行广播 {0}", i++.ToString());  
    24.                 s.SendTo(buffer, iep1);  
    25.                 Thread.Sleep(5000);  
    26.             }  
    27.         }  
    28.     }  
    29. }  


    对于UPD来说, 存在一个特定的广播地址 - 255.255.255.255, 广播数据都应该发送到这里。

      广播消息的目的IP地址是一种特殊IP地址,称为广播地址。

      广播地址由IP地址网络前缀加上全1主机后缀组成,如:192.168.1.255192.169.1.0 这个网络的广播地址;

      130.168.255.255 130.168.0.0 这个网络的广播地址。

      向全部为1IP地址(255.255.255.255)发送消息的话,那么理论上全世界所有的联网的计算机都能收得到了。

      但实际上不是这样的,一般路由器上设置抛弃这样的包,只在本地网内广播,所以效果和向本地网的广播地址发送消息是一样的。

      进行广播通信, 必须打开广播选项 SO_BROADCAST

    2. 客户端

    [csharp] view plain copy
    print?
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Text;  
    4. using System.Net.Sockets;  
    5. using System.Net;  
    6.   
    7. namespace Client  
    8. {  
    9. class Program  
    10.  {  
    11. static void Main(string[] args)  
    12.  {  
    13.  Socket m_s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  
    14.   
    15.  IPEndPoint iep = new IPEndPoint(IPAddress.Any, 4567);  
    16.  EndPoint ep = (EndPoint)iep;  
    17.  m_s.Bind(iep);  
    18.   
    19. byte[] buffer = new byte[1204];  
    20. while (true)  
    21.  {  
    22. int revc = m_s.ReceiveFrom(buffer, ref ep);  
    23. if (revc > 0)  
    24.  {  
    25. string data = Encoding.Unicode.GetString(buffer, 0, revc);  
    26.  Console.WriteLine(data);  
    27.  }  
    28.  }  
    29.  }  
    30.  }  
    31. }  


    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();

    0 0
    原创粉丝点击