什么是客户端应用程序在C#中在本地网络上查找服务器的最佳方式? [英] What is the best way for a client app to find a server on a local network in C#?
问题描述
客户端使用GenuineChannels连接到服务器(我们正在考虑切换到DotNetRemoting)。我的意思是find是获取要连接的服务器的IP和端口号。
The client connects to the server using GenuineChannels (we are considering switching to DotNetRemoting). What I mean by find is obtain the IP and port number of a server to connect to.
看起来像一个强力的方法将尝试网络上的每个IP尝试活动端口(甚至不确定是否可能),但必须有更好的方法。
It seems like a brute-force approach would be try every IP on the network try the active ports (not even sure if that's possible) but there must be a better way.
推荐答案
考虑广播特定UDP包。当一个或多个服务器看到广播的UDP分组时,它们发送回复。
Consider broadcasting a specific UDP packet. When the server or servers see the broadcasted UDP packet they send a reply. The client can collect the replies from all the servers and start connecting to them or based on an election algorithm.
查看客户端示例(未经测试的代码):
using System.Net;
using System.Net.Sockets;
[STAThread]
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Any, 8002));
socket.Connect(new IPEndPoint(IPAddress.Broadcast, 8001));
socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes("hello"));
int availableBytes = socket.Available;
if (availableBytes > 0)
{
byte[] buffer = new byte[availableBytes];
socket.Receive(buffer, 0, availableBytes, SocketFlags.None);
// buffer has the information on how to connect to the server
}
}
这篇关于什么是客户端应用程序在C#中在本地网络上查找服务器的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!