#!/usr/bin/php * @license PHP License * @package WB * @subpackage unittest */ include dirname(__FILE__) . '/../../../wbLoader.php'; class SocketClient { protected $server = null; public function __construct() { $this->config = WBClass::create('WBConfig'); $this->config->load('socketclient'); echo "pid: " . getmypid() . "\n"; } public function __destruct() { $this->disconnect(); } public function ping() { $this->connect(); echo "send: " . fputs($this->server, "ping\n") . "\n"; $lines = $this->read(); print_r($lines); $this->disconnect(); } protected function read() { $lines = array(); if (!$this->server) { return $lines; } while (!feof($this->server)) { $line = fgets($this->server, 8192); if ($line === false) { echo "Read error \n"; $this->disconnect(); return $lines; } $line = trim($line); if (empty($line)) { return $lines; } $lines[] = $line; } return $lines; } protected function disconnect() { if ($this->server) { echo "disconnect\n"; fclose($this->server); $this->server = null; } } protected function connect() { if ($this->server) { return true; } echo "connect "; // context $context = stream_context_create(); $proto = 'tcp'; if ($this->config->get('server/ssl', 0)) { $proto = 'ssl'; stream_context_set_option($context, 'ssl', 'allow_self_signed', true); stream_context_set_option($context, 'ssl', 'verify_peer', false); } // connect to socket $address = sprintf('%s://%s:%s' , $proto , $this->config->get('server/ip', '127.0.0.1') , $this->config->get('server/port', '8000')); $this->server = stream_socket_client($address , $errno , $errstr , 10 , STREAM_CLIENT_CONNECT , $context ); if (!$this->server) { echo "failed\n"; return false; } stream_set_blocking($this->server, 1); $lines = $this->read(); echo " '" . implode("\n", $lines) . "'\n"; return true; } } $c = new SocketClient(); $c->ping(); ?>