我尝试使用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文件的网页。
你说得对。这对我来说很愚蠢。我认为,因为应用程序以管理员权限运行,所以防火墙不是问题。奇怪的是,我从来没有收到Windows防火墙发送的消息是否阻止或允许该程序。好吧,谢谢。 – user1273708 2012-03-16 10:26:16
这应该赢得最短的答案奖励或徽章,但仍然轰炸目标:) – V4Vendetta 2012-03-16 10:33:11
哈!我不得不用不碎的空间来填充它,以使其达到最大长度! – spender 2012-03-16 12:48:12