Detect client disconnect with HttpListener

后端 未结 3 1586
独厮守ぢ
独厮守ぢ 2021-02-14 06:31

I have an application that uses HttpListener, I need to know when the client disconnected, right now I have all my code inside a try/catch block which is pretty ugly and not a g

3条回答
  •  感动是毒
    2021-02-14 06:58

    I'm having the same problem, I do a long sql query, and if user keeps pressing F5, it blows up.

    HttpListener do not expose its underlying socket so you can poll it.

    So I managed this workaround:

    IDbCommand cmd = LongSqlQuery();
    while (!taskCompleted)
    {
        try
        {
            //send disposable data at times to check connection
            byte[] dummy = new byte[1] { 0xFF };
            outputStream.Write(dummy,0,1);
    
            Task.Delay(100).Wait();
        }
        catch
        {
            //Client disconnect
            cmd.Cancel();
        }
    }
    
    //Redirect client to results page
    response.Redirect("http://yourserver.com/results?query=yourquery");
    

提交回复
热议问题