100 lines
2.3 KiB
PHP
100 lines
2.3 KiB
PHP
<?php
|
|
/**
|
|
* The SocketPool class that will handle all the sockets.
|
|
* Manages a pool of socket ressources with socket_select()
|
|
* @author jpt
|
|
* @package Socket
|
|
*/
|
|
class Socket_SocketPool {
|
|
|
|
/**
|
|
* Pool that contains socket ressources.
|
|
* @var array
|
|
*/
|
|
protected $sockets;
|
|
|
|
/**
|
|
* Creates sockets.
|
|
* @return void
|
|
*/
|
|
public function __construct() {
|
|
$this->sockets = array();
|
|
}
|
|
|
|
/**
|
|
* Closes all connections.
|
|
* @return void
|
|
*/
|
|
public function __destruct() {
|
|
unset($this->sockets);
|
|
}
|
|
|
|
/**
|
|
* Returns the amount of active sockets.
|
|
* @return int
|
|
*/
|
|
public function countSockets() {
|
|
return count($this->sockets);
|
|
}
|
|
|
|
/**
|
|
* Adds a socket to the pool
|
|
* @param ressource $add_socket
|
|
* @return void
|
|
*/
|
|
public function addSocket($add_socket) {
|
|
array_push($this->sockets, $add_socket);
|
|
}
|
|
|
|
/**
|
|
* Removes the given socket from the pool.
|
|
* The socket will be shutdown.
|
|
* @param ressource $remove_socket
|
|
* @return void
|
|
*/
|
|
public function removeSocket($remove_socket) {
|
|
foreach($this->sockets AS $key=>$socket) {
|
|
if($socket !== $remove_socket) {
|
|
continue;
|
|
} else {
|
|
unset($socket);
|
|
unset($this->sockets[$key]);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Creates a new TcpSocket and adds it to the pool.
|
|
* @throws Exception_SocketException
|
|
* @param boolean $IPv6 will determine whether the socket uses IPv4 or IPv6.
|
|
* @return ressource
|
|
*/
|
|
public function createTcpSocket($IPv6 = FALSE) {
|
|
$domain = ($IPv6) ? AF_INET6 : AF_INET;
|
|
$socket = socket_create($domain, SOCK_STREAM, SOL_TCP);
|
|
socket_set_block($socket);
|
|
if($socket === FALSE) throw new Exception_SocketException("socket_create() failed!", 1290273709);
|
|
$this->addSocket($socket);
|
|
return $socket;
|
|
}
|
|
|
|
/**
|
|
* Returns an array of sockets one can read from.
|
|
* @param array $read
|
|
* @param array $write
|
|
* @param array $except
|
|
* @param int $timeout
|
|
* @throws Exception_SocketException
|
|
* @return array
|
|
*/
|
|
public function select($read, $write, $except, $timeout = NULL) {
|
|
$n = socket_select($read, $write, $except, $timeout);
|
|
if($n === FALSE) throw new Exception_SocketException("socket_select() failed! - Error: " . socket_strerror(socket_last_error()), 1290273693);
|
|
if($n === 0) return array("read" => array(), "write" => array(), "except" => array());
|
|
return array("read" => $read, "write" => $write, "except" => $except);
|
|
}
|
|
|
|
|
|
}
|
|
?>
|