0
votes

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?

2

2 Answers

1
votes

I tested your code and it seems I got better results reading the socket with fread(). You also forgot the main loop(while(1), while(true) or for(;;).

Modifications to your code:

  • stream_socket_accept with @stream_socket_accept [sometimes you get warnings because "the connected party did not properly respond", which is, of course, the timeout of stream_socket_accept()]
  • Added the big while(1) { } loop
  • Changed the reading from the socket from $client_request = stream_get_contents($conn); to while( !preg_match('/\r?\n\r?\n/', $client_request) ) { $client_request .= fread($conn, 1024); }

Check the source code below (I used 8080 port because I already had an Apache listening on 80):

<?php

$s_socket_uri = 'tcp://localhost:8080';
$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;}

while(1)
{
    while($conn = @stream_socket_accept($s_socket, 60, $peer)) 
    {
        stream_set_blocking($conn, 0);
        echo "Connected with $peer.  Request info...\n";
        //    $client_request = stream_get_contents($conn);

        $client_request = "";
        // Read until double \r
        while( !preg_match('/\r?\n\r?\n/', $client_request) )
        {
            $client_request .= fread($conn, 1024);
        }

        if (!$client_request) 
        {
            trigger_error("Client request is empty!");
        }
        echo $client_request."\n\n";
        $headers = "HTTP/1.0 200 OK\n"
            ."Server: mine\n"
            ."Content-Type: text/html\n"
            ."\n";
        $body = "<h1>hello world</h1><br><br>".$client_request;
        if ((int) fwrite($conn, $headers . $body) < 1) {
            trigger_error("Write to socket failed!");
            }
    stream_socket_shutdown($conn, STREAM_SHUT_WR);
    }
}
-1
votes

Add sleep(1) after stream_set_blocking