一、廣播消息
由於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();
}
}
}