如何使服务器客户端通过局域网自动发现

How to make server client autodiscover over a lan

我有两个项目 "Server" 和 "Client" 通过 LAN 通信,

这是我的服务器代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServerClientProject
{
public partial class FormServer : Form
{
    private static Int32 port;
    private static string filePath;
    TcpListener server = new TcpListener(IPAddress.Any, port);

    public FormServer()
    {
        InitializeComponent();
    }

    private void FormServer_Load(object sender, EventArgs e)
    {
        File.WriteAllText("path.misc","");
        File.WriteAllText("nama.misc","");

        filePath = readPath();
        label1.Text = filePath;
        label2.Text = readNama();
        label3.Text = IPAddressCheck();
        label4.Text = UNCPathing.GetUNCPath(readPath());
        label5.Text = GetFQDN();

        bw.WorkerSupportsCancellation = true;
        bw.WorkerReportsProgress = true;
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

        if (bw.IsBusy != true)
        {
            bw.RunWorkerAsync();
        }
    }

    private static string IPAddressCheck()
    {
        IPHostEntry IPAddr;
        IPAddr = Dns.GetHostEntry(GetFQDN());
        IPAddress ipString = null;

        foreach (IPAddress ip in IPAddr.AddressList)
        {
            if (IPAddress.TryParse(ip.ToString(), out ipString) && ip.AddressFamily == AddressFamily.InterNetwork)
            {
                break;
            }
        }
        return ipString.ToString();
    }

    public static string GetFQDN()
    {
        string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName;
        string hostName = Dns.GetHostName();

        if (!hostName.EndsWith(domainName))  // if hostname does not already include domain name
        {
            hostName += "." + domainName;   // add the domain name part
        }

        return hostName;                    // return the fully qualified name
    }

    private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        lstProgress.Items.Add(e.UserState);
    }

    private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        if ((worker.CancellationPending == true))
        {
            e.Cancel = true;
        }
        else
        {
            try
            {
                // Set the TcpListener on port 1333.
                port = 1337;
                //IPAddress localAddr = IPAddress.Parse("127.0.0.1");
                TcpListener server = new TcpListener(IPAddress.Any, port);

                //label2.Text = IPAddressToString(ip);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[256];
                String data = null;

                // Enter the listening loop.
                while (true)
                {
                    bw.ReportProgress(0, "Waiting for a connection... ");
                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    bw.ReportProgress(0, "Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        bw.ReportProgress(0, String.Format("Received: {0}", data));

                        if (data == "file")
                        {

                        // Process the data sent by the client.

                            data = String.Format("Request: {0}", data);


                            byte[] mssg = System.Text.Encoding.ASCII.GetBytes(label4.Text);

                            // Send back a response.
                            stream.Write(mssg, 0, mssg.Length);
                            bw.ReportProgress(0, String.Format("Sent: {0}", data));
                            bw.ReportProgress(0, String.Format("File path : {0}", label4.Text));
                        }
                        else if (data == "nama")
                        {
                            byte[] mssg = System.Text.Encoding.ASCII.GetBytes(readNama());
                            stream.Write(mssg, 0, mssg.Length);
                        }
                        else if (data == "ip")
                        {
                            byte[] mssg = System.Text.Encoding.ASCII.GetBytes(GetFQDN());
                            stream.Write(mssg, 0, mssg.Length);
                        }
                    }

                    // Shutdown and end connection
                    client.Close();
                }
            }
            catch (SocketException se)
            {
                bw.ReportProgress(0, String.Format("SocketException: {0}", se));
            }
        }
    }

    private void FormServer_FormClosing(object sender, FormClosingEventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        savePath(openFileDialog1.FileName.ToString());
        saveNama(openFileDialog1.SafeFileName.ToString());

        //folderBrowserDialog1.ShowDialog();
        //savePath(folderBrowserDialog1.SelectedPath.ToString());

        label1.Text = readPath();
        label2.Text = readNama();
        label4.Text = UNCPathing.GetUNCPath(readPath());
    }

    private void savePath(string fPath)
    {
        string sPath = "Path.misc";

        File.WriteAllText(sPath, fPath);
    }

    private string readPath()
    {
        string readText = File.ReadAllText("Path.misc");
        return readText;
    }

    private void saveNama(string nama)
    {
        string sNama = "Nama.misc";

        File.WriteAllText(sNama, nama);
    }

    private string readNama()
    {
        string readText = File.ReadAllText("Nama.misc");
        return readText;
    }
}

}

这是我的客户

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Client
{
public partial class FormClient : Form
{
    public FormClient()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        label1.Text = IPAddressCheck();
        label2.Text = GetFQDN();
        label3.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

    }

    public void msg(string mesg)
    {
        lstProgress.Items.Add(">> " + mesg);
    }

    public static string GetFQDN()
    {
        string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName;
        string hostName = Dns.GetHostName();

        if (!hostName.EndsWith(domainName))  // if hostname does not already include domain name
        {
            hostName += "." + domainName;   // add the domain name part
        }

        return hostName;                    // return the fully qualified name
    }

    private static string IPAddressCheck()
    {
        IPHostEntry IPAddr;
        IPAddr = Dns.GetHostEntry(GetFQDN());
        IPAddress ipString = null;

        foreach (IPAddress ip in IPAddr.AddressList)
        {
            if (IPAddress.TryParse(ip.ToString(), out ipString) && ip.AddressFamily == AddressFamily.InterNetwork)
            {
                break;
            }
        }
        return ipString.ToString();
    }


    private void button1_Click(object sender, EventArgs e)
    {
        string message = textBox1.Text;
    try
    {
        // Create a TcpClient.
        // Note, for this client to work you need to have a TcpServer 
        // connected to the same address as specified by the server, port
        // combination.
        Int32 port = 1337;
        string IPAddr = textBox2.Text;
        TcpClient client = new TcpClient(IPAddr, port); //Unsure of IP to use.

        // Translate the passed message into ASCII and store it as a Byte array.
        Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

        // Get a client stream for reading and writing.
        //  Stream stream = client.GetStream();

        NetworkStream stream = client.GetStream();

        // Send the message to the connected TcpServer. 
        stream.Write(data, 0, data.Length);

        //lstProgress.Items.Add(String.Format("Sent: {0}", message));

        // Receive the TcpServer.response.

        // Buffer to store the response bytes.
        data = new Byte[256];

        // String to store the response ASCII representation.
        String responseData = String.Empty;

        // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(data, 0, data.Length);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            if (message == "file")
            {
                lstProgress.Items.Add(String.Format("{0}", responseData));
                fPath.getPath = (String.Format("{0}", responseData));
                label4.Text = UNCPathing.GetUNCPath(fPath.getPath);
            }
            else if(message == "nama")
            {
                lstProgress.Items.Add(String.Format("{0}", responseData));
                fPath.getNama = (String.Format("{0}", responseData));
            }

        // Close everything.
        stream.Close();
        client.Close();
    }
    catch (ArgumentNullException an)
    {
        lstProgress.Items.Add(String.Format("ArgumentNullException: {0}", an));
    }
    catch (SocketException se)
    {
        lstProgress.Items.Add(String.Format("SocketException: {0}", se));
    }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        //using (NetworkShareAccesser.Access(GetFQDN(), IPAddressCheck(), "arif.hidayatullah28@gmail.com", "971364825135win8"))
        //{

        //    File.Copy("\\"+label1.Text+"\TestFolder\"+fPath.getNama+"", @"D:\movie\"+ fPath.getNama+"", true);

        //}
    }

    private void button3_Click(object sender, EventArgs e)
    {
        string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\ARIF-PC\aaaaaaaaaa\MsAccess.accdb; Jet OLEDB:Database Password=dbase;";

        string cmdText = "SELECT kode, deskripsi, stok, Harga FROM [Barang] ORDER BY kode DESC";

        OleDbConnection conn = new OleDbConnection(connString);
        OleDbCommand cmd = new OleDbCommand(cmdText, conn);

        try
        {
            conn.Open();

            cmd.CommandType = CommandType.Text;
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataTable barang = new DataTable();
            da.Fill(barang);
            dataGridView1.DataSource = barang;
        }
        finally
        {
            conn.Close();
        }
    }
}

}

但是如你所见,我必须知道服务器的 ip 地址,有没有办法让服务器和客户端自动发现??

我试过了,在一台 PC 上工作,但在 LAN 上失败了。
This that I've tried

抱歉我的英语不好

在客户端发送 UDP 广播 192.168.1.255(假设您在 class C 网络 192.168.1/24 上运行)。服务器然后监听来自任何客户端的广播,然后将定向 UDP 数据包发送回客户端。客户端正在侦听并解码包含服务器地址的数据包。

这个 link C# How to do Network discovery using UDP Broadcast 和一些 Google Fu 将产生许多如何实现这个的例子。