Bryan Duxbury | 17115d7 | 2010-08-12 16:59:19 +0000 | [diff] [blame] | 1 | <?php |
| 2 | |
| 3 | include_once $GLOBALS['THRIFT_ROOT'].'/transport/TServerTransport.php'; |
| 4 | include_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php'; |
| 5 | |
| 6 | /** |
| 7 | * Socket implementation of a server agent. |
| 8 | * |
| 9 | * @package thrift.transport |
| 10 | */ |
| 11 | class TServerSocket extends TServerTransport { |
| 12 | |
| 13 | /** |
| 14 | * Handle for the listener socket |
| 15 | * |
| 16 | * @var resource |
| 17 | */ |
| 18 | private $listener_; |
| 19 | |
| 20 | /** |
| 21 | * Port for the listener to listen on |
| 22 | * |
| 23 | * @var int |
| 24 | */ |
| 25 | private $port_; |
| 26 | |
| 27 | /** |
| 28 | * Timeout when listening for a new client |
| 29 | * |
| 30 | * @var int |
| 31 | */ |
| 32 | private $acceptTimeout_ = 30000; |
| 33 | |
| 34 | /** |
| 35 | * Host to listen on |
| 36 | * |
| 37 | * @var string |
| 38 | */ |
| 39 | private $host_; |
| 40 | |
| 41 | /** |
| 42 | * ServerSocket constructor |
| 43 | * |
| 44 | * @param string $host Host to listen on |
| 45 | * @param int $port Port to listen on |
| 46 | * @return void |
| 47 | */ |
| 48 | public function __construct($host = 'localhost', $port = 9090) { |
| 49 | $this->host_ = $host; |
| 50 | $this->port_ = $port; |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Sets the accept timeout |
| 55 | * |
| 56 | * @param int $acceptTimeout |
| 57 | * @return void |
| 58 | */ |
| 59 | public function setAcceptTimeout($acceptTimeout) { |
| 60 | $this->acceptTimeout_ = $acceptTimeout; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Opens a new socket server handle |
| 65 | * |
| 66 | * @return void |
| 67 | */ |
| 68 | public function listen() { |
| 69 | $this->listener_ = stream_socket_server('tcp://' . $this->host_ . ':' . $this->port_); |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * Closes the socket server handle |
| 74 | * |
| 75 | * @return void |
| 76 | */ |
| 77 | public function close() { |
| 78 | @fclose($this->listener_); |
| 79 | $this->listener_ = null; |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Implementation of accept. If not client is accepted in the given time |
| 84 | * |
| 85 | * @return TSocket |
| 86 | */ |
| 87 | protected function acceptImpl() { |
| 88 | $handle = @stream_socket_accept($this->listener_, $this->acceptTimeout_ / 1000.0); |
| 89 | if(!$handle) return null; |
| 90 | |
| 91 | $socket = new TSocket(); |
| 92 | $socket->setHandle($handle); |
| 93 | |
| 94 | return $socket; |
| 95 | } |
| 96 | } |