什么是客户端应用程序来找到在C#中的本地网络上的服务器的最佳方式? [英] What is the best way for a client app to find a server on a local network in C#?
问题描述
客户端连接到使用GenuineChannels(我们正在考虑转换到DotNetRemoting)服务器。我的意思的发现是获取服务器的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屋!