设为首页 加入收藏

TOP

C# socket udp广播
2015-11-10 13:44:52 来源: 作者: 【 】 浏览:7
Tags:socket udp 广播

一、广播消息


  由于Tcp是有连接的,所以不能用来发送广播消息。发送广播消息,必须用到Udp,Udp可以不用建立连接而发送消息。广播消息的目的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)发送消息的话,那么理论上全世界所有的联网的计算机都能收得到了。但实际上不是这样的,一般路由器上设置抛弃这样的包,只在本地网内广播,所以效果和向本地网的广播地址发送消息是一样的。


  利用udp广播可以实现像cs中建立服务器后,客户端可以收到服务器消息从而进行连接。


二、服务端


开启线程不断广播自己ip地址等信息,等待客户端接收


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;


namespace scoket_udp_服务器
{
? ? class Program
? ? {
? ? ? ? private static Socket sock;
? ? ? ? private static IPEndPoint iep1;
? ? ? ? private static byte[] data;
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
? ? ? ? ? ? ProtocolType.Udp);
? ? ? ? ? ? //255.255.255.255
? ? ? ? ? ? iep1 =
? ? ? ? ? ? new IPEndPoint(IPAddress.Broadcast, 9050);


? ? ? ? ? ? string hostname = Dns.GetHostName();
? ? ? ? ? ? data = Encoding.ASCII.GetBytes(hostname);


? ? ? ? ? ? sock.SetSocketOption(SocketOptionLevel.Socket,
? ? ? ? ? ? SocketOptionName.Broadcast, 1);


? ? ? ? ? ? Thread t = new Thread(BroadcastMessage);
? ? ? ? ? ? t.Start();
? ? ? ? ? ? //sock.Close();


? ? ? ? ? ? Console.ReadKey();


? ? ? ? }


? ? ? ? private static void BroadcastMessage()
? ? ? ? {
? ? ? ? ? ? while (true)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? sock.SendTo(data, iep1);
? ? ? ? ? ? ? ? Thread.Sleep(2000);
? ? ? ? ? ? }
? ? ? ? ? ?
? ? ? ? }


? ? }
}


三、客户端


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;


namespace socket客户端udp
{
? ? class Program
? ? {
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? Socket sock = new Socket(AddressFamily.InterNetwork,
? ? ? ? ? ? SocketType.Dgram, ProtocolType.Udp);
? ? ? ? ? ? IPEndPoint iep =
? ? ? ? ? ? new IPEndPoint(IPAddress.Any, 9050);
? ? ? ? ? ? sock.Bind(iep);
? ? ? ? ? ? EndPoint ep = (EndPoint)iep;
? ? ? ? ? ? Console.WriteLine("Ready to receive…");


? ? ? ? ? ? byte[] data = new byte[1024];
? ? ? ? ? ? int recv = sock.ReceiveFrom(data, ref ep);
? ? ? ? ? ? string stringData = Encoding.ASCII.GetString(data, 0, recv);


? ? ? ? ? ? Console.WriteLine("received: {0} from: {1}",
? ? ? ? ? ? stringData, ep.ToString());? ? ? ? ?
? ? ? ? ? ? sock.Close();


? ? ? ? ? ? Console.ReadKey();
? ? ? ? }
? ? }
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇JavaScript之数组去重 下一篇回调函数在C/C++中的使用

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: