Не удается просмотреть веб-страницу с точки доступа, созданной в C # и HTTP-сервером, на устройстве клиента WiFi? - PullRequest
0 голосов
/ 01 июля 2018

Моей целью было обмениваться документами через WiFi, без подключения к интернету. Я начал с создания горячей точки, используя этот учебник здесь .

Затем я создал простой HTTP-сервер, используя различные учебные пособия онлайн.

Наконец, префикс HTTP - это IP-адрес ноутбука (тот, на котором я запустил точку доступа) на порту 1800.

Я успешно подключился к точке доступа, но при вводе IP-адреса ноутбука и порта в URL-адресе браузера клиента он не загружается и, наконец, выдает ошибку тайм-аута.

Когда я ввожу то же самое (IP-адрес хоста и номер порта в URL-адресе браузера), я получаю веб-страницу.

Извините за то, что вы немного абстрактны, не могли бы вы указать, где я иду не так?

Почему клиент не показывает веб-страницу, обслуживаемую хостом?

Исходный код:

class Program
{
    #region Main
    static void Main(string[] args)
    {
        Console.WriteLine("Starting Hotspot and http server");
        var th = new Task(() =>
        {
            Hotspot hotSpot = new Hotspot();
            hotSpot.CreateHotSpot("Test", "123456789");
            hotSpot.StartHotSpot();


            String ip = hotSpot.getIp();

            HttpServer httpServer = new HttpServer(ip);

            httpServer.Start();
        });
        th.Start();
        Console.ReadLine();
    }
    #endregion

    /// <summary>
    /// Create ,start ,stop Hotspot.
    /// share internet at the same time
    /// </summary>
    #region Hotspot
    class Hotspot
    {
        private string message = "";
        private dynamic netsharingmanager = null;
        private dynamic everyConnection = null;
        private bool hasnetsharingmanager = false;

        ProcessStartInfo ps = null;

        #region constructor
        public Hotspot()
        {
            ps = new ProcessStartInfo("cmd.exe");
            ps.UseShellExecute = false;
            ps.RedirectStandardOutput = true;
            ps.CreateNoWindow = true;
            ps.FileName = "netsh";


            //sharing 
            netsharingmanager = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.HNetShare.1"));
            if (netsharingmanager == null)
            {
                Console.WriteLine( "HNetCfg.HNetShare.1 was not found \n");
                hasnetsharingmanager = true;
            }
            else
            { hasnetsharingmanager = false; }

            if (netsharingmanager.SharingInstalled == false)
            {
                Console.WriteLine( "Sharing on this platform is not available \n");
                hasnetsharingmanager = false;
            }
            else
            { hasnetsharingmanager = true; }

            if (hasnetsharingmanager)
            { everyConnection = netsharingmanager.EnumEveryConnection; }
        }
        #endregion

        //check internet
        #region Check for internet
        public static bool CheckForInternetConnection()
        {
            try
            {
                using (var client = new WebClient())
                {
                    using (client.OpenRead("https://google.com/"))
                    { return true; }
                }
            }
            catch { return false; }
        }
        #endregion

        #region start Hotspot
        public void StartHotSpot()
        {
            ps.Arguments = "wlan start hosted network";
            ExecuteCommand(ps);
            Console.WriteLine("Starting Hotspot");

            //check for connected clients
            var th = new Task(() =>
            {
                while (true)
                {
                    HotSpotDetails details = new HotSpotDetails();
                    List<String> MacAddr = details.Mac_connected_devices();

                    Console.WriteLine("\n\n---------------------------------");
                    foreach (var item in MacAddr)
                    {
                        Console.WriteLine("Connected Device Mac = {0}", item);
                    }
                    Console.WriteLine("---------------------------------\n\n");
                    Thread.Sleep(100000);
                }
            });
            th.Start();
         }
        #endregion

        #region Create hot spot
        public void CreateHotSpot(string ssid_par, string key_par)
        {

            ps.Arguments = string.Format("wlan set hostednetwork mode=allow ssid={0} key={1}", ssid_par, key_par);
            ExecuteCommand(ps);
            Console.WriteLine("Creating hotspot name {0}",ssid_par);
        }
        #endregion

        #region Stop hotspot
        public void stop()
        {
            ps.Arguments = "wlan stop hosted network";
            ExecuteCommand(ps);
        }
        #endregion


        #region  shareinternet
        public void Shareinternet(string pubconnectionname, string priconnectionname, bool isenabled)
        {
            bool hascon = false;
            dynamic thisConnection = null;
            dynamic connectionprop = null;

            if (everyConnection == null)
            {
                everyConnection = netsharingmanager.EnumEveryConnection;
            }
            try
            {
                foreach (dynamic connection in everyConnection)
                {
                    thisConnection = netsharingmanager.INetSharingConfigurationForINetConnection(connection);
                    connectionprop = netsharingmanager.NetConnectionProps(connection);

                    Console.WriteLine("connectionprop name = {0} and pubconnectionname = {1}", connectionprop.name, pubconnectionname);
                    if (connectionprop.name == pubconnectionname) //public connection
                    {
                        hascon = true;
                        Console.WriteLine( string.Format("Setting ICS Public  {0} on connection: {1}\n", isenabled, pubconnectionname));
                        Console.WriteLine("Setting ICS Public  {0} on connection: {1}\n", isenabled, pubconnectionname);
                        if (isenabled)
                        {
                            thisConnection.EnableSharing(0);
                        }
                        else
                        {
                            thisConnection.DisableSharing();
                        }
                    }
                    if (connectionprop.Name == priconnectionname) //private connection
                    {
                        hascon = true;
                        Console.WriteLine( string.Format("Setting ICS Private  {0} on connection: {1}\n", isenabled, pubconnectionname));
                        Console.WriteLine("Setting ICS Private  {0} on connection: {1}\n", isenabled, pubconnectionname);
                        if (isenabled)
                        {
                            thisConnection.EnableSharing(1);

                        }
                        else
                        {
                            thisConnection.DisableSharing();
                        }
                    }
                    if (!hascon)
                    {
                        this.message += "no connection found";
                        Console.WriteLine("no connection found");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Hey an err in hotspot {0}", e);

            }
        }
        #endregion

        #region
        public string getIp()
        {
            string host_name = Dns.GetHostName();
            string ip = string.Empty;
            var host = Dns.GetHostEntry(host_name);
            foreach (var ip_ in host.AddressList)
            {
                if (ip_.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    ip = ip_.ToString();
                }
            }
            Console.WriteLine("\n -->my host name is {0} and my ip is {1} ", host_name, ip);
            return ip;
        }
        #endregion
        #region Execute command
        private void ExecuteCommand(ProcessStartInfo ps)
        {
            bool isExecuted = false;
            try
            {
                using (Process p = Process.Start(ps))
                {
                    message += p.StandardOutput.ReadToEnd() + "\n";
                    p.WaitForExit();
                    isExecuted = true;
                }
            }
            catch (Exception e)
            {
                message = "errorr -- >";
                message += e.Message;
                isExecuted = false;

            }

        }
        #endregion

    }
    #endregion

    /// <summary>
    /// get the hotspot details eg connected clients
    /// </summary>
    #region Hotspot Details
    class HotSpotDetails
    {
        //mac address list
        List<String> mac_address_list = new List<string>();
        #region GetMacAddr upto
        private List<string> GetMacAddr(string output)
        {
            //split_string.Substring(0, split_string.LastIndexOf(uptoword));

            string mac = string.Empty;
            List<string> mac_ad = new List<string>();

            string[] lines = output.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string line in lines)
            {
                if (line.Contains("Authenticated")) //"Number of clients"))
                {

                    mac = line.Substring(0, line.LastIndexOf("Authenticated"));
                    mac_ad.Add(mac.Replace(" ", string.Empty));
                }
            }
            return mac_ad;

        }
        #endregion

        #region get mac address of connected devices 
        public List<String> Mac_connected_devices()
        {
            String output = Console_command("netsh", "wlan show hosted");
            // Console.WriteLine("1------>{0}", output);
            mac_address_list = GetMacAddr(output);
            foreach (string item in mac_address_list)
            {
                Console.WriteLine("mac list item-number  = {0}", item);
            }
            return mac_address_list;
        }
        #endregion
        #region command line func 
        private string Console_command(string command, string args)
        {
            string output = string.Empty;

            ProcessStartInfo processStartInfo = new ProcessStartInfo(command, args);
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.UseShellExecute = false;

            processStartInfo.CreateNoWindow = true;

            Process proc = new Process
            {
                StartInfo = processStartInfo
            };

            proc.Start();

            output = proc.StandardOutput.ReadToEnd();


            return output;
        }
        #endregion


    }
    #endregion

    /// <summary>
    /// start and stop the http server at port 1800.
    /// </summary>
    #region HttpServer
    class HttpServer
    {
        public static HttpListener listener = new HttpListener();
        int port = 1800;
        String MyIp;
        Socket serverSocket = null;
        int backlog = 4;
        List<Socket> client = new List<Socket>();
        byte[] Buffer = new byte[1024];


        public HttpServer(String IpAddress)
        {
            this.MyIp = IpAddress;
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }


        //start http server
        public void Start()
        {

            System.Console.WriteLine("http://localhost:{0}/", port);
            System.Console.WriteLine("http://{0}:{1}/", MyIp, port);

           // String Localformart = String.Format("http://localhost:{0}/", port);
            String Gloabalformart = String.Format("http://{0}:{1}/", MyIp, port);

            //add prefix
           // listener.Prefixes.Add(Localformart);
            listener.Prefixes.Add(Gloabalformart);

            if (listener.IsListening)
            { listener.Stop(); }

            listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;

            listener.Start();

            if (listener.IsListening)
            { Console.WriteLine("Http serever listening"); }
            else { Console.WriteLine("Http serever not listening ?"); }

            int requestCounter = 0;

            while (listener.IsListening)
            {
                try
                {
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerResponse response = context.Response;

                    requestCounter++;
                    Console.WriteLine("Request counter {0}", requestCounter);
                    //webpage requested by browser
                    String WebPage = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath; //+ "webpage\\"; // String.Empty;

                    Console.WriteLine("Path to wbpage = {0} \n", WebPage);
                    if (string.IsNullOrEmpty(WebPage))
                    {
                        WebPage = "index.html";
                    }

                    // TextReader tr = new StreamReader(WebPage);
                    FileStream tr = new FileStream(WebPage, FileMode.Open, FileAccess.ReadWrite);


                    using (BinaryReader rds = new BinaryReader(tr))
                    {
                        var message = rds.ReadBytes(Convert.ToInt32(tr.Length));
                        //transform into byte array
                        // byte[] buffer = Encoding.UTF8.GetBytes(message);

                        //set up the message lent
                        response.ContentLength64 = message.Length;
                        //create a stream to send the message
                        Stream st = response.OutputStream;
                        st.Write(message, 0, message.Length);
                        //close the connection
                        context.Response.Close();
                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine("Error in Http server is listening");
                }
            }
        }

    }
    #endregion
}

Краткое описание вышеуказанного кода:

Есть три класса

  1. Hotspot
    • Горячая точка создает запуск и остановку Горячей точки.
  2. Информация о точках доступа
    • Сведения о точке доступа в основном получают все IP-адреса подключенных устройств.
  3. HTTP-сервер
    • HTTP-сервер запускает HTTP-сервер с двумя префиксами 127.0.0.1:1800 и {My IP Address}: 1800.

Конечно, в папке отладки есть страница index.html.

Когда я пингую IP-адрес подключенного устройства, я получаю ответ. Однако, когда я пингую IP-адрес хоста с гостевого устройства, я не получаю ответ.

Кроме того, веб-страница отображается нормально с локального хоста, но с устройства, подключенного к точке доступа, я получаю ошибку тайм-аута из Chrome.

Почему веб-страница не отображается на гостевом устройстве?

...