.NET 简单实现广播

148 篇文章 1 订阅
代码

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数据包:

 

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. 服务端

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


 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值