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