Jump to content

Socket server, input timeout


Pimeau

Recommended Posts

I have a simple socket server, and I wish to prompt the user for more data if he takes more than say, 5 seconds entering it. The problem is that the socket_write with the alert takes place AFTER he enters something, not after 5 seconds have passed. Any help would be greatly appreciated.

 

Here's the code:

 

#!/opt/lampp/bin/php -q

<?php

set_time_limit(0);

ob_implicit_flush();

 

$address = 0;

$port = 9050;

 

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {

    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";

}

 

if (socket_bind($sock, $address, $port) === false) {

    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";

}

 

if (socket_listen($sock, 5) === false) {

    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";

}

 

do {

    if (($msgsock = socket_accept($sock)) === false) {

        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";

        break;

    }

    /* Send instructions. */

    $msg = "\nWelcome to the PHP Test Server. \n" .

        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";

    socket_write($msgsock, $msg, strlen($msg));

    $inicio = time();

    do {

        usleep(50);

        if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {

            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";

            break 2;

        }

        // if more than 5 seconds have passed, demand more data

        // THE ALERT IS WRITTEN AFTER THE I GET SOMETHING FROM THE USER EVEN IF 5 SECONDS HAVE PASSED ???

        if ( (time() - $inicio) > 5 ) {

            $alerta = 'I am waiting for you to write something!\n';

            $inicio = time();

            socket_write($msgsock, $alerta, strlen($alerta));

        }

        if (!$buf = trim($buf)) {

            continue;

        }

        if ($buf == 'quit') {

            break;

        }

        if ($buf == 'shutdown') {

            socket_close($msgsock);

            break 2;

        }

        $talkback = "PHP: You said '$buf'.\n";

        socket_write($msgsock, $talkback, strlen($talkback));

        echo "$buf\n";

    } while (true);

    socket_close($msgsock);

} while (true);

socket_close($sock);

?>

[code=php:0]

Link to comment
https://forums.phpfreaks.com/topic/121318-socket-server-input-timeout/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.