现在的位置: 首页 > 综合 > 正文

C# 广播通信

2012年01月22日 ⁄ 综合 ⁄ 共 1553字 ⁄ 字号 评论关闭

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

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

    利用广播(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 这个网络的广播地址。

  向全部为1IP地址(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. 效果

抱歉!评论已关闭.