2012-07-08 98 views
0

我是新手c#開發人員 - 嘗試編寫一個簡單的win7服務。

服務應該啓動HTTPListener並偵聽傳入的瀏覽器請求,當收到請求時它會返回響應並繼續偵聽其他請求。 我不需要處理並行性,因爲一次只能有一個請求(並且很短)。使用HTTPListener的Win7服務在一個請求後停止響應

我用下面的代碼,但在第一個響應後服務停止響應。 我可能需要一個循環,但我不熟悉API,所以我可能也錯在我正在做的事情上。

謝謝你的幫助。

protected override void OnStart(string[] args) 
    { 
     HttpListener listener = new HttpListener(); 
     listener.Prefixes.Add("http://localhost:9999/"); 
     listener.Start(); 

     listener.BeginGetContext(new AsyncCallback(OnRequestReceive), listener); 
    } 

    private void OnRequestReceive(IAsyncResult result) 
    { 
     HttpListener listener = (HttpListener)result.AsyncState; 
     HttpListenerContext context = listener.EndGetContext(result); 
     HttpListenerResponse response = context.Response; 
     byte[] buff = {1,2,3}; 

     response.Close(buff, true); 
    } 

回答

4

你快到了!收到一個請求後,您需要開始聆聽另一個請求。

private void OnRequestReceive(IAsyncResult result) 
{ 
    HttpListener listener = (HttpListener)result.AsyncState; 

    HttpListenerContext context = listener.EndGetContext(result); 
    HttpListenerResponse response = context.Response; 
    byte[] buff = {1,2,3}; 

    response.Close(buff, true); 

    // ---> start listening for another request 
    listener.BeginGetContext(new AsyncCallback(OnRequestReceive), listener); 
} 
+0

謝謝!像魔術一樣工作。在一行代碼上經歷了許多小時的挫折:) – user1283002 2012-07-08 21:21:48

相關問題