Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

remoting - What is the best way for a client app to find a server on a local network in C#?

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

See example for client (untested code):


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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...