Pimeau Posted August 25, 2008 Share Posted August 25, 2008 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] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.