c# socket udp广播

时间:2023-03-08 16:39:40

一、广播消息

  由于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, ); string hostname = Dns.GetHostName();
data = Encoding.ASCII.GetBytes(hostname); sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, ); Thread t = new Thread(BroadcastMessage);
t.Start();
//sock.Close(); Console.ReadKey(); } private static void BroadcastMessage()
{
while (true)
{
sock.SendTo(data, iep1);
Thread.Sleep();
} } }
}

三、客户端

 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, );
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive…"); byte[] data = new byte[];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, , recv); Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
sock.Close(); Console.ReadKey();
}
}
}