Reputation: 7900
I use this code to write Windows Service that work as local http request server.
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();
}
}
And i have some issues with this code:
First of all in the data
string i get stuff like this after i write this URL in my browser 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
And i want to know how can i get only the helloWorld
from this example.
And the second issue is that i want the server will give response to the browser and it only give me to close the connection.
Upvotes: 2
Views: 7179
Reputation: 9467
I asked something similiar a few days ago. Better implement the HTTPListener-Class. Makes life way easier.
See this Example: http://msdn.microsoft.com/de-de/library/system.net.httplistener%28v=vs.85%29.aspx
Your HelloWorld is retrieved like this:
HttpListenerContext context = listener.GetContext(); // Waits for incomming request
HttpListenerRequest request = context.Request;
string url = request.RawUrl; // This would contain "/helloworld"
And if you want to wait for more than just one request either implement the Asynchronos way or do it like this:
new Thread(() =>
{
while(listener.IsListening)
{
handleRequest(listener.GetContext());
}
});
...
void handleRequest(HttpListenerContext context) { // Do stuff here }
That codesample came out of my head. It will probably take some fumbling arround for it to work nicely but i hope you get the idea.
Upvotes: 6