如何使服务器客户端通过局域网自动发现 [英] How to make server client autodiscover over a lan

查看:66
本文介绍了如何使服务器客户端通过局域网自动发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个通过局域网进行通信的项目服务器"和客户端",

I have two project "Server" and "Client" that communicate 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地址,有没有一种方法可以使服务器和客户端自动发现?

but as you can see, I have to know the server ip address, is there a way to make the server and client autodiscover??

我已经尝试过,可以在一台PC上工作,但是在LAN上却失败了.
我尝试过的

I've try this, worked with one PC but with a LAN it failed.
This that I've tried

对不起,我的英语不好

推荐答案

在客户端上发送UDP广播192.168.1.255(假定您在C类网络192.168.1/24上进行操作).然后,服务器侦听来自任何客户端的广播,然后将定向的UDP数据包发送回客户端.客户端正在侦听此消息,并对包含服务器地址的数据包进行解码.

On the client send a UDP broadcast 192.168.1.255 (this assumes you are operating on a class C network 192.168.1/24). The server then listens for the broadcast from any clients and then sends back a directed UDP packet to the client. The client is listening for this and decodes the packet which contains the address of the server.

此链接 C#如何使用以下方法进行网络发现UDP广播和一些Google Fu会提供许多实现该示例的示例.

This link C# How to do Network discovery using UDP Broadcast and some Google Fu will produce many examples of how to implement this.

这篇关于如何使服务器客户端通过局域网自动发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆