簡體   English   中英

如何使服務器客戶端通過局域網自動發現

[英]How to make server client autodiscover over a 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卻失敗了。
我嘗試過的

對不起,我的英語不好

在客戶端上發送UDP廣播192.168.1.255(假設您在C類網絡192.168.1 / 24上運行)。 然后,服務器偵聽來自任何客戶端的廣播,然后將定向的UDP數據包發送回客戶端。 客戶端正在偵聽此消息,並對包含服務器地址的數據包進行解碼。

此鏈接C#如何使用UDP廣播和一些Google Fu 進行網絡發現將提供許多有關如何實現此目的的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM