Delfer has asked for the wisdom of the Perl Monks concerning the following question:

I want to build a server socket for HTTP.There are two questions on this matter. 1.How does my server socket get the data POST(ed) from a form in web? 2.How do I know client has closed his socket,so I can close my socket in child process in time? waitting for answer... Thank you.

Replies are listed 'Best First'.
Re: Questions on socket
by btrott (Parson) on Apr 16, 2000 at 09:25 UTC
    1. You read the data from the client socket. Essentially, the order goes something like this:
    1. the server accepts a request from the client and receives a filehandle
    2. the server reads from the filehandle just as it would from any filehandle (ie., using <>, or read, etc.)
    3. you read the GET or POST line, then the request headers, then a blank line (end of headers); you should look for a Content-Length header, which will tell you how long the POST content should be. Then read that much content.
    2. I'm not sure exactly how you can trap a client closing the socket; do you mean if the socket is closed normally, or do you mean if the socket is closed because the client hit the Stop button, for example? In the former case, you should basically close the socket once you've written out the response, I think. In the latter case, I *think* you can try to catch a $SIG{PIPE} on write attempts to the client. So set up a $SIG{PIPE} to catch such writes and close the socket.

    You might also take a look at HTTP::Daemon (part of LWP), if not to use it, then just to study it for your own uses.

      Based on my work with Jellybean, I think SIGPIPE only occurs when there's an error, like a broken pipe. The underlying TCP/IP implementation seems to handle closes automatically. At least, I never had to do anything with them that the IO::Socket library didn't do for me.
        I actually meant trying to catch a SIGPIPE when the client prematurely hits the Stop button in the browser, not when the socket is closed normally. If the server tries to write to a client that has disconnected from the socket, a SIGPIPE should occur, and it can be caught by the web server. Of course, you only get a SIGPIPE once you try to write to the socket, so if you're in the midst of some lengthy operation (where you don't write back to the client), you won't catch it right away.

        I believe this is how one previously determined that clients pressed the Stop button under mod_perl, although after Apache 1.3.6, there's now a better way of doing it (checking the return value of $r->print).