note 23098 modified in function.socket-select by aidan

From: Date: Fri, 21 Jan 2005 06:14:28 +0000
Subject: note 23098 modified in function.socket-select by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-83715@lists.php.net to get a copy of this message
hello, i just made a class which acts similiar to Perl's IO::Select in order to make socket selecting very easy your script should look something like that: <?php $server = new Server; $client = new Client; for (;;) { foreach ($select->can_read(0) as $socket) { if ($socket == $client->socket) { // New Client Socket $select->add(socket_accept($client->socket)); } else { //there's something to read on $socket } } } ?> you should of course implement some routines to detect broken sockets and remove them from the select object. you can also do output buffering and check in the main-loop for sockets that are ready to write <?php class select { var $sockets; function select($sockets) { $this->sockets = array(); foreach ($sockets as $socket) { $this->add($socket); } } function add($add_socket) { array_push($this->sockets,$add_socket); } function remove($remove_socket) { $sockets = array(); foreach ($this->sockets as $socket) { if($remove_socket != $socket) $sockets[] = $socket; } $this->sockets = $sockets; } function can_read($timeout) { $read = $this->sockets; socket_select($read,$write = NULL,$except = NULL,$timeout); return $read; } function can_write($timeout) { $write = $this->sockets; socket_select($read = NULL,$write,$except = NULL,$timeout); return $write; } } ?> --was-- hello, i just made a class which acts similiar to Perl's IO::Select in order to make socket selecting very easy your script should look something like that: $server = new Server; $client = new Client; for (;;) { foreach ($select->can_read(0) as $socket) { if ($socket == $client->socket) { // New Client Socket $select->add(socket_accept($client->socket)); } else { //there's something to read on $socket } } } you should of course implement some routines to detect broken sockets and remove them from the select object. you can also do output buffering and check in the main-loop for sockets that are ready to write class select { var $sockets; function select($sockets) { $this->sockets = array(); foreach ($sockets as $socket) { $this->add($socket); } } function add($add_socket) { array_push($this->sockets,$add_socket); } function remove($remove_socket) { $sockets = array(); foreach ($this->sockets as $socket) { if($remove_socket != $socket) $sockets[] = $socket; } $this->sockets = $sockets; } function can_read($timeout) { $read = $this->sockets; socket_select($read,$write = NULL,$except = NULL,$timeout); return $read; } function can_write($timeout) { $write = $this->sockets; socket_select($read = NULL,$write,$except = NULL,$timeout); return $write; } } http://php.net/manual/en/function.socket-select.php

« previous php.notes (#83715) next »