2013-04-10 57 views
2

我使用此代码编写作为本地http请求服务器工作的Windows服务。Windows服务上的本地Http服务器

public void StartMe() 
    { 
     System.Net.IPAddress localAddr = System.Net.IPAddress.Parse("127.0.0.1"); 
     System.Net.Sockets.TcpListener server = new System.Net.Sockets.TcpListener(localAddr, 1234); 
     server.Start(); 
     Byte[] bytes = new Byte[1024]; 
     String data = null; 
     while (RunThread) 
     { 
      System.Net.Sockets.TcpClient client = server.AcceptTcpClient(); 
      data = null; 
      System.Net.Sockets.NetworkStream stream = client.GetStream(); 
      stream.Read(bytes, 0, bytes.Length); 
      data = System.Text.Encoding.ASCII.GetString(bytes); 

      System.IO.StreamWriter sw = new System.IO.StreamWriter("c:\\MyLog.txt", true); 
      sw.WriteLine(data); 
      sw.Close(); 

      client.Close(); 
     } 
    } 

,我有这个代码的一些问题:所有在data字符串 首先,我得到这样的东西后,我在我的浏览器http://127.0.0.1:1234/helloWorld

GET /helloWorld HTTP/1.1 
Host: 127.0.0.1:1234 
Connection: keep-alive 
Cache-Control: max-age=0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31 
Accept-Encoding: gzip,deflate,sdch 
Accept-Language: he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4 
Accept-Charset: windows-1255,utf-8;q=0.7,*;q=0.3 

写这篇文章的网址,我想知道我怎样才能从这个例子中得到helloWorld。 而第二个问题是,我想服务器将给予浏览器的响应,它只给我关闭连接。

+0

这里没有任何与HTTP服务器类似的东西。它是一个监听套接字,它接受连接并将请求写入文件,仅此而已。如果你想自己实现一个HTTP服务器(并且相信我,你不需要),从2616开始看看各种RFC。如果你解释你的最终目标是什么,那么可以选择更好的解决方案,比如@ CSharpie的答案指向HttpListener类。更好的是,甚至可以只写一个.aspx或MVC页面,全部取决于你想要做什么。 – CodeCaster 2013-04-10 17:58:29

回答

3

几天前我问了一些类似的东西。 更好地实现HTTPListener-Class。让生活更轻松。

看到这个例子: http://msdn.microsoft.com/de-de/library/system.net.httplistener%28v=vs.85%29.aspx

你的HelloWorld检索这样的:

HttpListenerContext context = listener.GetContext(); // Waits for incomming request 
HttpListenerRequest request = context.Request; 
string url = request.RawUrl; // This would contain "/helloworld" 

如果你想等待更多的不仅仅是一个请求要么实现Asynchronos方式或像这样做:

new Thread(() => 
{ 
    while(listener.IsListening) 
    { 
     handleRequest(listener.GetContext()); 
    } 

}); 
... 

void handleRequest(HttpListenerContext context) { // Do stuff here } 

这个codesample出现在我脑袋里。它可能需要一些摸索才能很好地工作,但我希望你能明白。

+0

感谢重播,但我如何开始HTTP服务器运行? – MTA 2013-04-11 09:46:03

+0

listener.Start(); while(listener.IsListening){var ctx = listener.GetContext()} Getcontext方法然后为每个请求返回一个contextObject。 – CSharpie 2013-04-11 09:54:22