开发者

How to know when to close socket when dealing with HTTP clients?

How can I know when to close the socket of an HTTP client (I mean a browser is connecting to my TCP socket server). Everything works perfect but in other for the browser to show what the server has sent, i have to shutdown the server (or call socket.Close()).

It works fine if I call (socket.Close()) but I just don't know when.? I don't want to call close in a middle of a request otherwise the browser would have to reload to connect to the server again开发者_开发百科.


You need to shutdown your end of the socket so the client knows there will be no more data. You also need to read any pending data because if you call Close() right away the client will get a reset (TCP RST).

With the code above, once the client closes its end or the timeout you define is up, the connection will finally be closed on our end.

What I did a long time ago was this (for Mono's ASP.NET server):

    void LingeringClose ()
    {
        int waited = 0;

        if (!Connected)
            return;

        try {
            Socket.Shutdown (SocketShutdown.Send);
            DateTime start = DateTime.UtcNow;
            while (waited < max_useconds_to_linger) {
                int nread = 0;
                try {
                    if (!Socket.Poll (useconds_to_linger, SelectMode.SelectRead))
                        break;

                    if (buffer == null)
                        buffer = new byte [512];

                    nread = Socket.Receive (buffer, 0, buffer.Length, 0);
                } catch { }

                if (nread == 0)
                    break;

                waited += (int) (DateTime.UtcNow - start).TotalMilliseconds * 1000;
            }
        } catch {
            // ignore - we don't care, we're closing anyway
        }
    }


HTTP is rather complex protocol. RFC 2616 (which you must read if you are implementing an HTTP server) defines version 1.1 and specifically talks about connection handling in section 8.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜