-1
如果我不知道服務器正在運行的端口,是否可以發送用於搜索服務器應用程序的廣播?或者我必須檢查每個端口?用未知端口發送廣播
要發送一個簡單的廣播,我發現在互聯網下面的代碼:
服務器
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Console.Write("Running server..." + Environment.NewLine);
server.Bind(new IPEndPoint(IPAddress.Any, 48000));
while (true)
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
byte[] buffer = new byte[1000];
server.ReceiveFrom(buffer, ref tempRemoteEP);
Console.Write("Server got '" + buffer[0] + "' from " + tempRemoteEP.ToString() + Environment.NewLine);
Console.Write("Sending '2' to " + tempRemoteEP.ToString() +
Environment.NewLine);
server.SendTo(new byte[] { 2 },
tempRemoteEP);
}
客戶
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, 48000);
//Allow sending broadcast messages
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
//Send message to everyone
client.SendTo(new byte[] { 1 }, AllEndPoint);
Console.Write("Client send '1' to " + AllEndPoint.ToString() +
Environment.NewLine);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
byte[] buffer = new byte[1000];
string serverIp;
try
{
//Recieve from server. Don't wait more than 3000 milliseconds.
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 3000);
client.ReceiveFrom(buffer, ref tempRemoteEP);
Console.Write("Client got '" + buffer[0] + "' from " +
tempRemoteEP.ToString() + Environment.NewLine);
//Get server IP (ugly)
serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
}
catch
{
//Timout. No server answered.
serverIp = "?";
}
Console.Write("ServerIp: " + serverIp + Environment.NewLine);
Console.ReadLine();
但我不知道,我的服務器使用端口48000
。
謝謝!
謝謝你,我寫了一個應用服務器,它將把所有的數據傳遞給客戶端。由於客戶自己安裝客戶端,我想實現一種「服務器搜索」功能,因此他們只需從列表中選擇應用程序服務器。 – BendEg 2015-02-06 14:06:06
因此,默認使用端口48000。掃描網絡中主機的全部65000個端口可能不僅速度慢,而且可能不會讓網絡管理員滿意,因爲此行爲會加載網絡,並且還可能會警告某些入侵檢測系統。 – thomai 2015-02-09 07:08:08