2012-03-16 70 views
4

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

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作为轻量级服务器,通过一些动态init参数,clientaccesspolicy.xml和一个简单的移动HTML页面提供带有Silverlight XAP文件的网页。

回答

18

防火墙         

+1

你说得对。这对我来说很愚蠢。我认为,因为应用程序以管理员权限运行,所以防火墙不是问题。奇怪的是,我从来没有收到Windows防火墙发送的消息是否阻止或允许该程序。好吧,谢谢。 – user1273708 2012-03-16 10:26:16

+8

这应该赢得最短的答案奖励或徽章,但仍然轰炸目标:) – V4Vendetta 2012-03-16 10:33:11

+10

哈!我不得不用不碎的空间来填充它,以使其达到最大长度! – spender 2012-03-16 12:48:12

0

我也想过先防火墙。然而,当我的终点问题:

从教程中,我有一个像下面

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

此代码只能在本地且仅当您使用本地代码。为了能够使用IP,我把它改成

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

这一次通过IP地址请求的工作,但服务器没有从另一个IP远程请求做出响应。是什么让我的工作对我来说是使用的不是本地主机和127.0.0.1星号(*​​),所以下面的代码:

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

就要离开这个在这里,如果有人绊倒在这个职位和我一样。