一、广播消息
由于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地址等信息,等待客户端接收
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Net; 6 using System.Net.Sockets; 7 using System.Threading; 8 using System.Threading.Tasks; 9 10 namespace scoket_udp_服务器 11 { 12 class Program 13 { 14 private static Socket sock; 15 private static IPEndPoint iep1; 16 private static byte[] data; 17 static void Main(string[] args) 18 { 19 sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 20 ProtocolType.Udp); 21 //255.255.255.255 22 iep1 = 23 new IPEndPoint(IPAddress.Broadcast, 9050); 24 25 string hostname = Dns.GetHostName(); 26 data = Encoding.ASCII.GetBytes(hostname); 27 28 sock.SetSocketOption(SocketOptionLevel.Socket, 29 SocketOptionName.Broadcast, 1); 30 31 Thread t = new Thread(BroadcastMessage); 32 t.Start(); 33 //sock.Close(); 34 35 Console.ReadKey(); 36 37 } 38 39 private static void BroadcastMessage() 40 { 41 while (true) 42 { 43 sock.SendTo(data, iep1); 44 Thread.Sleep(2000); 45 } 46 47 } 48 49 } 50 }
三、客户端
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Net; 6 using System.Net.Sockets; 7 using System.Threading.Tasks; 8 9 namespace socket客户端udp 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 Socket sock = new Socket(AddressFamily.InterNetwork, 16 SocketType.Dgram, ProtocolType.Udp); 17 IPEndPoint iep = 18 new IPEndPoint(IPAddress.Any, 9050); 19 sock.Bind(iep); 20 EndPoint ep = (EndPoint)iep; 21 Console.WriteLine("Ready to receive…"); 22 23 byte[] data = new byte[1024]; 24 int recv = sock.ReceiveFrom(data, ref ep); 25 string stringData = Encoding.ASCII.GetString(data, 0, recv); 26 27 Console.WriteLine("received: {0} from: {1}", 28 stringData, ep.ToString()); 29 sock.Close(); 30 31 Console.ReadKey(); 32 } 33 } 34 }