note 57335 rejected from function.socket-listen by nicobn

From: Date: Tue, 03 Jul 2007 19:56:33 +0000
Subject: note 57335 rejected from function.socket-listen by nicobn
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-128193@lists.php.net to get a copy of this message
Note Submitter: Tarik Kettani ---- For a UDP listening server in php, let's say you need something to listen for 2 seconds and give you all the received data in that time .. beware of the cpu load of a while(true) or while (time() <= $timeout) kinda thing ... i managed to go from a 100% cpu usage to something more reasonable by introducing a little microsleep between the socket_recv polls : $sock2 = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if(!socket_bind($sock2, $your_ip, 666)) { socket_close($sock2); die( 'socket_bind failed: '.socket_strerror(socket_last_error())); } socket_set_nonblock($sock2); $timeout = time() + (2); // 3 seconds timeout while (time() <= $timeout) { while (@socket_recv($sock2, $data, 8192, 0)) { // do something useful with $data :) } usleep(100000); // 100ms delay keeps the doctor away } socket_close($sock2); bonne chance :)

« previous php.notes (#128193) next »