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

代码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?
  1. using   System;
  2. using   System.Net;
  3. using   System.Net.Sockets;
  4. using   System.Text;
  5. public   class   UDPMulticastSender   {
  6. private   static   IPAddress   GroupAddress   =
  7. IPAddress.Parse("224.168.100.2");
  8. private   static   int   GroupPort   =   11000;
  9. private   static   void   Send(   String   message)   {
  10. UdpClient   sender   =   new   UdpClient();
  11. IPEndPoint   groupEP   =   new   IPEndPoint(GroupAddress,GroupPort);
  12. try   {
  13. Console.WriteLine("Sending   datagram   :   {0}",   message);
  14. byte[]   bytes   =   Encoding.ASCII.GetBytes(message);
  15. sender.Send(bytes,   bytes.Length,   groupEP);
  16. sender.Close();
  17. }   catch   (Exception   e)   {
  18. Console.WriteLine(e.ToString());
  19. }
  20. }
  21. public   static   int   Main(String[]   args)   {
  22. Send(args[0]);
  23. return   0;
  24. }

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?
  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. namespace _5._2_广播通信
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  14. s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  15. byte[] buffer = Encoding.Unicode.GetBytes("Hello World");
  16. IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 4567);//255.255.255.255
  17. int i = 0;
  18. while (true)
  19. {
  20. Console.WriteLine("正在进行广播 {0}", i++.ToString());
  21. s.SendTo(buffer, iep1);
  22. Thread.Sleep(5000);
  23. }
  24. }
  25. }
  26. }

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

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简单广播相关推荐

  1. java udp 多播 广播_Java UDP 广播与多播

    1.广播: 同一网段所有主机都能接收,前提是端口要监听 客户端发送广播,开启端口监听的服务端接收并打印消息 服务端程序: import java.io.IOException; import java ...

  2. 网络与通信程序设计-基于UDP的广播通信实例

    目录 实验内容和设计思想 实验的内容 UDP的设计思想 UDP的协议头部 UDP通信编程思想 UDP的工作流程 UDP编程收发函数 广播通信 广播模式设置 广播套接字 UDP Socket的使用过程 ...

  3. UDP --02--UDP广播数据

    设计模型 局域网UDP广播数据端UdpBroadCast.cpp #include <tchar.h> // _T宏 #include <stdio.h>// printf s ...

  4. java网络编程作业基于UDP简单聊天窗口,图形化界面,包含客户端和服务端

    //郑州轻工业大学 //题号:实验四 第二题 //题目:使用基于UDP的网络编程方法,完成客户端和服务器间的聊天功能.要求图形界面. java网络编程作业 基于UDP简单聊天窗口,图形化界面,包含客户 ...

  5. UDP IPv4广播地址计算(附Node.js示例代码)

    文章目录 目的 计算方法 示例代码 代码演示 总结 目的 UDP广播是比较常用的一种功能,应用方面来说经常用在设备发现等功能中.UDP广播需要知道广播地址,这篇文章将介绍通过IPv4地址和子网掩码来计 ...

  6. linux sendto 速度慢,UDP Socket 广播中sendto()耗时过长

    UDP Socket 广播中,sendto()将数据发送到一个结尾为"255"的IP地址,应用中发现sendto()函数耗时过长.参考了"http://topic.csd ...

  7. UDP协议报文分析和主动发送UDP简单实现

    UDP协议报文分析和主动发送UDP简单实现 前言 一.Wireshark 报文解析 1.UDP报文实例 2.报文格式分析 ①.以太网头 ②.IP头 ③.UDP头 二.UDP主动传输数据的实现方式 1. ...

  8. UDP、广播、多播与IGMP(七)

    (参考文献)TCP/IP详解,卷1:协议 UDP是一个简单的面向数据报的运输层协议:进程的每个输出操作都正好产生一个UDP数据报,并组装成一份待发送的IP数据报.UDp数据报封装成IP数据报格式如下图 ...

  9. UDP之广播搜索局域网内设备信息

    文章目录 UDP是什么? UDP核心API DatagramSocket构造方法介绍 DatagramSocket常用方法 DatagramPacket的构造方法 DatagramPacket的常用方 ...

最新文章

  1. WSL(windows subsystem for linux)安装错误:安装过程中遇到错误,但可以继续安装。组件: ‘WSL 内核‘ 错误代码: 0x80072f78解决方法
  2. Windows 软件授权管理工具检验Windows7激活状态和许可证详细信息
  3. 浙大计算机系学霸,国内三个“图灵班”,学霸中的尖子才能考得上,全是计算机人才!...
  4. apache 设置session超时时间_深入分析 Session 和 Cookie,看这篇就对了
  5. php 查文件sha1 内存不足,SHA是否足以检查文件重复? (PHP中的sha1_file)
  6. 我国自主播放软件暴风影音挑落微软
  7. java.util.list e_java.util 类 StackE - Java 中文参考手册
  8. Linux将字符串转化为float,C语言中如何将字符串转换成float和double类型
  9. 极客大学架构师训练营 加密技术 高可用系统的度量 高可用系统的架构 高可用系统的运维 第22课 听课总结
  10. ET7.0 腾讯云centos部署
  11. LIKE 多字段匹配 效率低下
  12. 途家2019校招笔试 1 求最大公约数和最小公倍数
  13. 使用DragonFly进行智能镜像分发
  14. dede标签详细的dede标签大全,dede标签在线学习
  15. Python爬虫入门好学吗?为什么?
  16. igd12um32xel.dll病毒
  17. 微信JS-SDK实现自定义分享功能,分享给朋友,分享到朋友圈
  18. 大数据毕设题目推荐 - 最新大数据毕设选题 - 毕业设计项目方向课题
  19. Linux下缓冲区溢出攻击的原理及对策
  20. seo全攻略_Shopify店铺SEO最全攻略(新手必看!!)

热门文章

  1. matlab算线性方程解,MATLAB计算方法3解线性方程组计算解法.pptx
  2. python实际应用方面的材料_python应用于哪些方面
  3. 计算机二级考点的选择题,2016年计算机二级考试试题选择题
  4. 详解MOS管、IGBT管,不看就亏大了!
  5. 【本质】你知道C语言编译的过程吗?
  6. python value函数_python 函数基础
  7. java语音开源_号外!号外!百度语音开源库更新了
  8. 句柄操作窗体_winform让窗体一直显示在桌面上以及FindWindow
  9. 用shell编写一个三角形图案
  10. Ubuntu 首次给root用户设置密码