简体   繁体   English

即使允许防火墙,HttpListener 也无法通过网络工作

[英]HttpListener won't work over network even with firewall allowed

I'm using the following code to add a http listener:我正在使用以下代码添加一个 http 侦听器:

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 a我什至添加了一个outgoing即将离任incoming 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.防火墙的传入规则允许连接,我使用netsh http add urlacl url="http://+:18991/" user=everyone添加了 URL,并以管理员权限启动了应用程序,但没有成功。

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:

    启动 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 :在 Windows 中打开Resource Monitor并确保端口存在并设置为Allowed, not limited

    资源监视器

  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:以如下方式启动HttpListener

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:运行ipconfig并检查您拥有的 IP 地址:

    在此处输入图片说明

  2. Ping your computer from the other computer on the network:从网络上的另一台计算机 Ping 您的计算机:

    在此处输入图片说明

  3. From the other computer, also test to send an HTTP request to your computer:在另一台计算机上,还测试向您的计算机发送 HTTP 请求:

    在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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