views:

51

answers:

2

Hi,

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.

+1  A: 

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
        }
    }
Gonzalo
Will this work even if I have a Asynchronous base socket to where as I can pass a new reference of socket to be shutdown or would I have to create a list of socket clients to test and perform shutdown?
Y_Y
I get an error that says: An attempt has made on a socket that has been shut down?...
Y_Y
The above code is used in a NetworkStream-derived class and is executed when Close() is explicitly called or the GC is finalizing the object. If the socket is asynchronous you might have to do a few changes.
Gonzalo
A: 

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.

Nikolai N Fetissov