C#实现 UDP简单广播
- 代码
- 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();
- });
- }
- }
代码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;
- }
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);
- }
- }
- }
- }
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. 客户端
- 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:
接收端:
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());
发送端:
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简单广播相关推荐
- java udp 多播 广播_Java UDP 广播与多播
1.广播: 同一网段所有主机都能接收,前提是端口要监听 客户端发送广播,开启端口监听的服务端接收并打印消息 服务端程序: import java.io.IOException; import java ...
- 网络与通信程序设计-基于UDP的广播通信实例
目录 实验内容和设计思想 实验的内容 UDP的设计思想 UDP的协议头部 UDP通信编程思想 UDP的工作流程 UDP编程收发函数 广播通信 广播模式设置 广播套接字 UDP Socket的使用过程 ...
- UDP --02--UDP广播数据
设计模型 局域网UDP广播数据端UdpBroadCast.cpp #include <tchar.h> // _T宏 #include <stdio.h>// printf s ...
- java网络编程作业基于UDP简单聊天窗口,图形化界面,包含客户端和服务端
//郑州轻工业大学 //题号:实验四 第二题 //题目:使用基于UDP的网络编程方法,完成客户端和服务器间的聊天功能.要求图形界面. java网络编程作业 基于UDP简单聊天窗口,图形化界面,包含客户 ...
- UDP IPv4广播地址计算(附Node.js示例代码)
文章目录 目的 计算方法 示例代码 代码演示 总结 目的 UDP广播是比较常用的一种功能,应用方面来说经常用在设备发现等功能中.UDP广播需要知道广播地址,这篇文章将介绍通过IPv4地址和子网掩码来计 ...
- linux sendto 速度慢,UDP Socket 广播中sendto()耗时过长
UDP Socket 广播中,sendto()将数据发送到一个结尾为"255"的IP地址,应用中发现sendto()函数耗时过长.参考了"http://topic.csd ...
- UDP协议报文分析和主动发送UDP简单实现
UDP协议报文分析和主动发送UDP简单实现 前言 一.Wireshark 报文解析 1.UDP报文实例 2.报文格式分析 ①.以太网头 ②.IP头 ③.UDP头 二.UDP主动传输数据的实现方式 1. ...
- UDP、广播、多播与IGMP(七)
(参考文献)TCP/IP详解,卷1:协议 UDP是一个简单的面向数据报的运输层协议:进程的每个输出操作都正好产生一个UDP数据报,并组装成一份待发送的IP数据报.UDp数据报封装成IP数据报格式如下图 ...
- UDP之广播搜索局域网内设备信息
文章目录 UDP是什么? UDP核心API DatagramSocket构造方法介绍 DatagramSocket常用方法 DatagramPacket的构造方法 DatagramPacket的常用方 ...
最新文章
- WSL(windows subsystem for linux)安装错误:安装过程中遇到错误,但可以继续安装。组件: ‘WSL 内核‘ 错误代码: 0x80072f78解决方法
- Windows 软件授权管理工具检验Windows7激活状态和许可证详细信息
- 浙大计算机系学霸,国内三个“图灵班”,学霸中的尖子才能考得上,全是计算机人才!...
- apache 设置session超时时间_深入分析 Session 和 Cookie,看这篇就对了
- php 查文件sha1 内存不足,SHA是否足以检查文件重复? (PHP中的sha1_file)
- 我国自主播放软件暴风影音挑落微软
- java.util.list e_java.util 类 StackE - Java 中文参考手册
- Linux将字符串转化为float,C语言中如何将字符串转换成float和double类型
- 极客大学架构师训练营 加密技术 高可用系统的度量 高可用系统的架构 高可用系统的运维 第22课 听课总结
- ET7.0 腾讯云centos部署
- LIKE 多字段匹配 效率低下
- 途家2019校招笔试 1 求最大公约数和最小公倍数
- 使用DragonFly进行智能镜像分发
- dede标签详细的dede标签大全,dede标签在线学习
- Python爬虫入门好学吗?为什么?
- igd12um32xel.dll病毒
- 微信JS-SDK实现自定义分享功能,分享给朋友,分享到朋友圈
- 大数据毕设题目推荐 - 最新大数据毕设选题 - 毕业设计项目方向课题
- Linux下缓冲区溢出攻击的原理及对策
- seo全攻略_Shopify店铺SEO最全攻略(新手必看!!)
热门文章
- matlab算线性方程解,MATLAB计算方法3解线性方程组计算解法.pptx
- python实际应用方面的材料_python应用于哪些方面
- 计算机二级考点的选择题,2016年计算机二级考试试题选择题
- 详解MOS管、IGBT管,不看就亏大了!
- 【本质】你知道C语言编译的过程吗?
- python value函数_python 函数基础
- java语音开源_号外!号外!百度语音开源库更新了
- 句柄操作窗体_winform让窗体一直显示在桌面上以及FindWindow
- 用shell编写一个三角形图案
- Ubuntu 首次给root用户设置密码