HTTPListener无法通过网络工作

时间:2012-03-16 10:20:02

标签: c# .net httplistener

我尝试使用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) ;
    }
}

此代码有问题,还是有其他问题?

我尝试使用管理员权限运行应用程序,但是当我在另一台计算机上浏览到计算机的IP地址(即192.168.1.100)时,我从未收到该请求。如果请求是从运行应用程序的同一台计算机发送的(使用“localhost”,“127.0.0.1”和“192.168.1.100”),则服务器可以正常工作。 Pinging工作正常。我也试过了nginx,这在网络上运行得很好。

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

2 个答案:

答案 0 :(得分:23)

防火墙

答案 1 :(得分:0)

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

从教程中我得到了如下代码

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/",
    // ...
};

如果有人像我一样偶然发现这篇文章,就把它留在这里。