简体   繁体   中英

HttpListener won't work over network even with firewall allowed

I'm using the following code to add a http listener:

public class WebServer
{
    private readonly HttpListener _listener = new HttpListener();
    private readonly Func<HttpListenerRequest, HttpListenerResponse, string> _responderMethod;

    public WebServer(string[] prefixes, Func<HttpListenerRequest, HttpListenerResponse, string> method)
    {
        if (!HttpListener.IsSupported)
            throw new NotSupportedException(
                "Needs Windows XP SP2, Server 2003 or later.");

        // URI prefixes are required, for example 
        // "http://localhost:8080/index/".
        if (prefixes == null || prefixes.Length == 0)
            throw new ArgumentException("prefixes");

        // A responder method is required
        if (method == null)
            throw new ArgumentException("method");

        foreach (string s in prefixes)
            _listener.Prefixes.Add(s);

        _responderMethod = method;
        _listener.Start();
    }

    public WebServer(Func<HttpListenerRequest, HttpListenerResponse, string> method, params string[] prefixes)
        : this(prefixes, method) { }

    public void Run()
    {
        ThreadPool.QueueUserWorkItem((o) =>
        {
            //Console.WriteLine("Webserver running...");
            try
            {
                while (_listener.IsListening)
                {
                    ThreadPool.QueueUserWorkItem((c) =>
                    {
                        var ctx = c as HttpListenerContext;
                        try
                        {
                            string rstr = _responderMethod(ctx.Request, ctx.Response);
                            byte[] buf = Encoding.UTF8.GetBytes(rstr);
                            ctx.Response.ContentLength64 = buf.Length;
                            ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                        }
                        catch { } // suppress any exceptions
                        finally
                        {
                            // always close the stream
                            ctx.Response.OutputStream.Close();
                        }
                    }, _listener.GetContext());
                }
            }
            catch { } // suppress any exceptions
        });
    }

    public void Stop()
    {
        _listener.Stop();
        _listener.Close();
    }
}

static class Program
{
    public const int PORT = 18991;

    [STAThread]
    static void Main()
    {
        WebServer ws = new WebServer(SendResponse, "http://+:" + PORT + "/");
        ws.Run();
        Application.Run(new Form1());
        ws?.Stop();
    }
    private static string SendResponse(HttpListenerRequest request, HttpListenerResponse response)
    {
        return "ok";
    }
}

This works fine on the local machine, however it won't listen to request from other devices inside the network. I even added aoutgoingincoming rule to the firewall allowing the connection, I added the URL using netsh http add urlacl url="http://+:18991/" user=everyone and started the application with admin rights, but no success.

How can I allow requests from remote devices inside the LAN?

Here are steps that you can try and see if they help:

  1. Start Visual Studio as administrator:

    启动 Visual Studio

  2. Start your application in debug mode.

  3. Open Resource Monitor in Windows and ensure that the port is present and set to Allowed, not restricted :

    资源监视器

  4. If not, add an inbound firewall rule for the port:

    在此处输入图片说明

    Allow it on all domains:

    在此处输入图片说明

    Allow programs:

    在此处输入图片说明

    Allow the connection:

    在此处输入图片说明

  5. Start HttpListener in the following way:

using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace HttpTestServer
{
    public class MainWindow
    {
        private readonly HttpListener _httpListener;

        public MainWindow()
        {
            _httpListener = new HttpListener();
            _httpListener.Prefixes.Add("http://*:9191/");
            Task.Run(Start);
        }

        public async Task Start()
        {
            _httpListener.Start();
            while (true)
            {
                var context = await _httpListener.GetContextAsync();

                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    await sw.FlushAsync();
                }
            }
        }
    }
}
  1. Run ipconfig and check what IP address you have:

    在此处输入图片说明

  2. Ping your computer from the other computer on the network:

    在此处输入图片说明

  3. From the other computer, also test to send an HTTP request to your computer:

    在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM