Below is partial code to an experimental http server app I'm building from scratch from a PHP CLI script (Why? Because I have too much time on my hands). The example below more closely matches PHP's manual page on this function. The problem I'm getting is when connecting to this server app via a browser (Firefox or IE8 from two separate systems tested so far), the browser sends an empty request payload to the server and aborts roughly every 1 in 6 page loads.
The server console displays the "Connected with [client info]" each time. However, about 1 in 6 connections will result in a "Client request is empty" error. No error is given telling the header/body response write to the socket failed. The browser will generally continue to read what I give it, but this isn't usable as I can't fulfill the client's intended request without knowing what it is.
<?php $s_socket_uri = 'tcp://localhost:80'; // establish the server on the above socket $s_socket = stream_socket_server($s_socket_uri, $errno, $errstr, 30) OR trigger_error("Failed to create socket: $s_socket_uri, Err($errno) $errstr", E_USER_ERROR); $s_name = stream_socket_get_name($s_socket, false) OR trigger_error("Server established, yet has no name. Fail!", E_USER_ERROR); if (!$s_socket || !$s_name) {return false;} /* Wait for connections, handle one client request at a time Though to not clog up the tubes, maybe a process fork is needed to handle each connection? */ while($conn = stream_socket_accept($s_socket, 60, $peer)) { stream_set_blocking($conn, 0); // Get the client's request headers, and all POSTed values if any echo "Connected with $peer. Request info...\n"; $client_request = stream_get_contents($conn); if (!$client_request) { trigger_error("Client request is empty!"); } echo $client_request."\n\n"; // just for debugging /* <Insert request handling and logging code here> */ // Build headers to send to client $send_headers = "HTTP/1.0 200 OK\n" ."Server: mine\n" ."Content-Type: text/html\n" ."\n"; // Build the page for client view $send_body = "<h1>hello world</h1>"; // Make sure the communication is still active if ((int) fwrite($conn, $send_headers . $send_body) < 1) { trigger_error("Write to socket failed!"); } // Response headers and body sent, time to end this connection stream_socket_shutdown($conn, STREAM_SHUT_WR); } ?>
Any solution to bring down the number of unintended aborts down to 0, or any method to get more stable communication going? Is this solvable on my server's end, or just typical browser behavior?