首页 文章

HTTPListener无法通过网络工作

提问于
浏览
4

我尝试使用System.Net.HTTPListener创建一个简单的HTTP服务器,但它不接收来自网络中其他计算机的连接 . 示例代码:

class HTTPServer
{
    private HttpListener listener;
    public HTTPServer() { }
    public bool Start()
    {
        listener = new HttpListener();
        listener.Prefixes.Add("http://+:80/");
        listener.Start();
        listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
        return true;
    }
    private static void ListenerCallback(IAsyncResult result)
    {
        HttpListener listener = (HttpListener)result.AsyncState;
        listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
        Console.WriteLine("New request.");

        HttpListenerContext context = listener.EndGetContext(result);
        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;

        byte[] page = Encoding.UTF8.GetBytes("Test");

        response.ContentLength64 = page.Length;
        Stream output = response.OutputStream;
        output.Write(page, 0, page.Length);
        output.Close();
    }
}
class Program
{
    static void Main(string[] args)
    {
        HTTPServer test = new HTTPServer();
        test.Start();
        while (true) ;
    }
}

这段代码有问题,还是有其他问题?

我've tried running the application with administrator privileges, but when I browse to the computer'在另一台计算机上的IP地址(即192.168.1.100),我从未收到过请求 . 如果请求是从运行应用程序的同一台计算机发送的(使用"localhost","127.0.0.1"和"192.168.1.100"),则服务器可以正常工作 . Pinging工作正常 . 我也试过nginx,这在网络上运行得很好 .

我正在使用HTTPListener作为轻量级服务器来提供带有Silverlight XAP文件的网页,其中包含一些动态init参数,clientaccesspolicy.xml和一个简单的移动HTML页面 .

2 回答

  • 21

    火墙

  • 0

    我还想到了第一个防火墙 . 但是我的 endpoints 问题在哪里:

    从教程我得到了如下代码

    String[] endpoints = new String[] {
        "http://localhost:8080/do_something/",
        // ...
    };
    

    此代码仅在本地使用,并且仅在您使用localhost时才有效 . 为了能够使用IP,我将其更改为

    String[] endpoints = new String[] {
        "http://127.0.0.1:8080/do_something/",
        // ...
    };
    

    这次ip adress的请求工作,但服务器没有响应来自另一个ip的远程请求 . 让我为我工作的是使用星号(*)而不是localhost和127.0.0.1,因此以下代码:

    String[] endpoints = new String[] {
        "http://*:8080/do_something/",
        // ...
    };
    

    如果有人像我一样偶然发现这个帖子,就把它留在这里 .

相关问题