/** * Constructor. * * @param array $config Socket configuration, which will be merged with the base configuration * @see CakeSocket::$_baseConfig */ public function __construct($config = array()) { $this->config = array_merge($this->_baseConfig, $config); if (!is_numeric($this->config['protocol'])) { $this->config['protocol'] = getprotobyname($this->config['protocol']); } }
private function _connect() { if ($this->connection = socket_create($this->socket_domain, SOCK_STREAM, $this->socket_domain > 1 ? getprotobyname('tcp') : 0)) { if (socket_connect($this->connection, $this->socket_address, $this->socket_port)) { $this->setNonBlock(); // $this->connection); // устанавливаем неблокирующий режим работы сокета return $this->connected = true; } else { $error = socket_last_error($this->connection); socket_clear_error($this->connection); switch ($error) { case SOCKET_ECONNREFUSED: case SOCKET_ENOENT: // если отсутствует файл сокета, либо соединиться со слушающим сокетом не удалось - возвращаем false $this->disconnect(); return false; default: // в иных случаях кидаем необрабатываемое исключение throw new \Exception(socket_strerror($error)); } } } // @TODO delete next line... trigger_error('Client connect failed', E_USER_ERROR); return false; }
/** * testConstruct method * * @return void */ public function testConstruct() { $this->Socket = new CakeSocket(); $config = $this->Socket->config; $this->assertSame($config, array( 'persistent' => false, 'host' => 'localhost', 'protocol' => getprotobyname('tcp'), 'port' => 80, 'timeout' => 30 )); $this->Socket->reset(); $this->Socket->__construct(array('host' => 'foo-bar')); $config['host'] = 'foo-bar'; $this->assertSame($this->Socket->config, $config); $this->Socket = new CakeSocket(array('host' => 'www.cakephp.org', 'port' => 23, 'protocol' => 'udp')); $config = $this->Socket->config; $config['host'] = 'www.cakephp.org'; $config['port'] = 23; $config['protocol'] = 17; $this->assertSame($this->Socket->config, $config); }
/** * Gets the OrientSocket, and establishes the connection if required. * * @return \PhpOrient\Protocols\Binary\OrientSocket * * @throws SocketException * @throws PhpOrientWrongProtocolVersionException */ public function connect() { if (!$this->connected) { if (empty($this->hostname) && empty($this->port)) { throw new SocketException('Can not initialize a connection ' . 'without connection parameters'); } if (!extension_loaded("sockets")) { throw new SocketException('Can not initialize a connection ' . 'without socket extension enabled. Please check you php.ini'); } $this->_socket = @socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_set_block($this->_socket); socket_set_option($this->_socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => self::READ_TIMEOUT, 'usec' => 0)); socket_set_option($this->_socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => self::WRITE_TIMEOUT, 'usec' => 0)); $x = @socket_connect($this->_socket, $this->hostname, $this->port); if (!is_resource($this->_socket) || $x === false) { throw new SocketException($this->getErr() . PHP_EOL); } $protocol = Reader::unpackShort($this->read(2)); if ($protocol > $this->protocolVersion) { throw new PhpOrientWrongProtocolVersionException('Protocol version ' . $protocol . ' is not supported.'); } //protocol handshake $this->protocolVersion = $protocol; $this->connected = true; } return $this; }
/** * Method send * * @param string $raw_text * * @return string $return_text */ public function send($raw_text) { if (!empty($raw_text)) { $this->raw_text = $raw_text; $xw = new xmlWriter(); $xw->openMemory(); $xw->startDocument('1.0'); $xw->startElement('wordsegmentation'); $xw->writeAttribute('version', '0.1'); $xw->startElement('option'); $xw->writeAttribute('showcategory', '1'); $xw->endElement(); $xw->startElement('authentication'); $xw->writeAttribute('username', $this->username); $xw->writeAttribute('password', $this->password); $xw->endElement(); $xw->startElement('text'); $xw->writeRaw($this->raw_text); $xw->endElement(); $xw->endElement(); $message = iconv("utf-8", "big5", $xw->outputMemory(true)); //send message to CKIP server set_time_limit(60); $protocol = getprotobyname("tcp"); $socket = socket_create(AF_INET, SOCK_STREAM, $protocol); socket_connect($socket, $this->server_ip, $this->server_port); socket_write($socket, $message); $this->return_text = iconv("big5", "utf-8", socket_read($socket, strlen($message) * 3)); socket_shutdown($socket); socket_close($socket); } return $this->return_text; }
protected function connectSocket() { if (filter_var($this->host, FILTER_VALIDATE_IP)) { $ip = $this->host; } else { $ip = gethostbyname($this->host); if ($ip == $this->host) { throw new MongoConnectionException(sprintf('couldn\'t get host info for %s', $this->host)); } } // For some reason, PHP doesn't currently allow resources opened with // fsockopen/pfsockopen to be used with socket_* functions, but HHVM does. if (defined('HHVM_VERSION')) { $this->socket = pfsockopen($ip, $this->port, $errno, $errstr, $this->connectTimeoutMS / 1000); if ($this->socket === false) { $this->socket = null; throw new MongoConnectionException(sprintf("unable to connect to {$ip}:{$this->port} because: %s", "{$errstr} ({$errno})")); } } else { $this->socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname("tcp")); if (!$this->socket) { throw new MongoConnectionException(sprintf('error creating socket: %s', socket_strerror(socket_last_error()))); } $connected = socket_connect($this->socket, $ip, $this->port); if (!$connected) { throw new MongoConnectionException(sprintf("unable to connect to {$ip}:{$this->port} because: %s", socket_strerror(socket_last_error()))); } } }
/** * Começa a escutar conexões e processar as demais funcionalidades * @param int $port número da porta * @throws EndPointException */ public function listen($port) { $this->port = $port; /* @var resource cria o socket que escutará conexões */ $this->serverSocket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('TCP')); if (!socket_set_option($this->serverSocket, SOL_SOCKET, SO_REUSEADDR, 1)) { echo socket_strerror(socket_last_error($this->serverSocket)); exit; } /* seta o host e a porta */ if (!@socket_bind($this->serverSocket, 0, $this->port)) { throw new EndPointException("socket_bind() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket))); } /* inicia a escuta de conexões */ if (!@socket_listen($this->serverSocket)) { throw new EndPointException("socket_listen() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket))); } /* cria um array de sockets e adiciona o serverSocket no array */ $this->sockets = array($this->serverSocket); $this->loopPrincipal(); /* Fecha todos os sockets e encerra a aplicação */ foreach ($this->sockets as $socket) { if (get_resource_type($socket) == "Socket") { socket_close($socket); } } }
public function mServer() { $sock = socket_create(AF_INET, SOCK_DGRAM, getprotobyname('udp')); $mIP = '239.255.255.250'; if (!socket_bind($sock, $mIP, 1900)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not bind socket : [{$errorcode}] {$errormsg} \n"); } socket_set_option($sock, IPPROTO_IP, MCAST_JOIN_GROUP, array("group" => '239.255.255.250', "interface" => 0)); while (1) { echo "Waiting for data ... \n"; socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port); echo "{$remote_ip} : {$remote_port} -- " . $buf; $query = $this->parseHeaders($buf); if (!isset($query["m-search"])) { continue; } $response = "HTTP/1.1 200 OK\r\n"; $response .= "CACHE-CONTROL: max-age=1810\r\n"; $response .= "DATE: " . date("r") . "\r\n"; $response .= "EXT:\r\n"; $response .= "LOCATION: http://192.168.7.123:9000/TMSDeviceDescription.xml\r\n"; $response .= "SERVER: Linux/3.x, UPnP/1.1, fheME/0.6\r\n"; $response .= "ST: urn:fheme.de:service:X_FIT_HomeAutomation:1\r\n"; $response .= "USN: uuid:f6da16ab-0d1b-fe1c-abca-82aacf4afcac::urn:fheme.de:service:X_FIT_HomeAutomation:1\r\n"; $response .= "Content-Length: 0\r\n"; $response .= "\r\n"; //Send back the data to the client socket_sendto($sock, $response, strlen($response), 0, $mIP, $remote_port); } socket_close($sock); }
/** * 創建SOCKET * @author wave */ protected static function create() { self::$sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); if (!self::$sock) { exit('create socket error'); } }
function initIcecastComm($serv = '127.0.0.1', $port = 8000, $mount = "/setme", $pass = "******") { global $iceGenre, $iceName, $iceDesc, $iceUrl, $icePublic, $icePrivate, $iceAudioInfoSamplerate, $iceAudioInfoBitrate, $iceAudioInfoChannels; // We're going to create a tcp socket. $sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_set_block($sock) or die("Blocking error: " . socket_strerror(socket_last_error($sock)) . " \n"); if (!$sock) { die("Unable to create socket! " . socket_strerror(socket_last_error($sock)) . " \n"); } else { // Connect to the server. echo "Connecting to {$serv} on port {$port}\n"; if (socket_connect($sock, $serv, $port)) { echo "Connection established! Sending login....\n"; $this->sendData($sock, "SOURCE {$mount} HTTP/1.0\r\n"); $this->sendLogin($sock, $pass); $this->sendData($sock, "User-Agent: icecastwebm-php\r\n"); $this->sendData($sock, "Content-Type: video/webm\r\n"); $this->sendData($sock, "ice-name: {$iceName}\r\n"); $this->sendData($sock, "ice-url: {$iceUrl}\r\n"); $this->sendData($sock, "ice-genre: {$iceGenre}\r\n"); $this->sendData($sock, "ice-public: {$icePublic}\r\n"); $this->sendData($sock, "ice-private: {$icePrivate}\r\n"); $this->sendData($sock, "ice-description: {$iceDesc}\r\n"); $this->sendData($sock, "ice-audio-info: ice-samplerate={$iceAudioInfoSamplerate};ice-bitrate={$iceAudioInfoBitrate};ice-channels={$iceAudioInfoChannels}\r\n"); $this->sendData($sock, "\r\n"); // Go into loop mode. $this->parseData($sock); $this->initStream($sock); // Start the stream. //die; } else { die("Unable to connect to server! " . socket_strerror(socket_last_error($sock)) . " \n"); } } }
public function __construct($ip, $port) { $this->IP = $ip; $this->Port = $port; $this->Socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname("tcp")); $this->Connected = false; SocketManager::AddSocket($this); }
/** * Constructor with an optional argument of a socket resource * * @param resource $socket A socket resource as returned by socket_create() or socket_accept() */ function SMTP_Server_Socket($socket = null) { $this->log = new SMTP_Server_Log(); $this->socket = $socket; $this->remote_address = ''; if (!$this->socket) { $this->socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); } }
/** * @return resource * @throws \Exception */ public function getConnection() { if (!empty($this->socket)) { return $this->socket; } $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($this->socket, getprotobyname('TCP'), TCP_NODELAY, 1); socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, ["sec" => self::STREAM_TIMEOUT, "usec" => 0]); if (!socket_connect($this->socket, $this->host, $this->port)) { throw new ConnectionException("Unable to connect to Cassandra node: {$this->host}:{$this->port}"); } return $this->socket; }
/** * * @throws Exception * @return resource */ public function getConnection() { if (!empty($this->socket)) { return $this->socket; } $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($this->socket, getprotobyname('TCP'), TCP_NODELAY, 1); foreach ($this->_options['socket'] as $optname => $optval) { socket_set_option($this->socket, SOL_SOCKET, $optname, $optval); } if (!socket_connect($this->socket, $this->_options['host'], $this->_options['port'])) { throw new Exception("Unable to connect to Cassandra node: {$this->_options['host']}:{$this->_options['port']}"); } return $this->socket; }
public function Startup() { $Host = "10.10.43.138"; $Proto = getprotobyname("tcp"); set_time_limit(0); $Socket = socket_create(AF_INET, SOCK_STREAM, $Proto) or dir("Create socket failed!!\n"); socket_bind($Socket, $Host, 5678) or die("Can not bind socket!!\n"); $Result = socket_listen($Socket); while (true) { $Client = socket_accept($Socket) or die("Can not read input!!\n"); $this->ResBind($Client); $this->ResUserInfo($Client); } socket_close($Socket); // close server }
public static function read($addr, $proto = 'udp') { $socket = socket_create(AF_INET, self::$proto[$proto], getprotobyname($proto)) or die('socket create error ' . socket_strerror(socket_last_error())); //socket_set_blocking($socket, 0);//0-非阻塞 1-阻塞 list($host, $port) = explode(':', $addr); socket_bind($socket, $host, $port) or die('socket bind error\\n'); socket_listen($socket, 4) or die('socket listen error\\n'); while (1) { $newsocket = socket_accept($socket) or die('socket accept error\\n'); //socket_write($newsocket, date('Y-m-d H:i:s')); if ($res = socket_read($newsocket, 8192)) { //sleep(5); var_dump(date('Y-m-d H:i:s'), $res); } } }
/** * 建立链接 * * @return boolean */ public function connect() { //应该用更合适的方法去判断连接是否已经建立 if ($this->sock == true) { return true; } $commonProtocol = getprotobyname("tcp"); $socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol); if (socket_connect($socket, $this->host, $this->port) == false) { $this->errno = ERR_REQUEST_CONNECT_FAILED; $this->error = "建立连接失败[{$this->host}:{$this->port}]"; return false; } $this->sock = $socket; return true; }
public function __construct($address = 'localhost', $port = 80) { ob_implicit_flush(); $this->socket_master = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); //socket_set_option($this->socket_master, SOL_SOCKET, SO_REUSEADDR, 1); //socket_bind($this->socket_master, $address, $port); //echo socket_strerror(socket_last_error()); //socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 2, 'usec' => 0)); $sc = socket_connect($this->socket_master, $address, $port); // socket_listen($this->socket_master); //echo socket_strerror(socket_last_error()); $this->make_hand_shake($this->socket_master); $this->connect($this->socket_master); //echo 'WebSocket Client Connected: ' . $address . ':' . $port . PHP_EOL; $p = $this->send('ping'); return $sc && $p != null; }
/** * Constructor. * * @param string $host * Hostname * @param float $timeout * Connect timeout * @param float $stream_timeout * Stream timeout */ public function __construct($host, $connect_timeout = 3, $stream_timeout = 10) { if (strstr($host, ':')) { $port = (int) substr(strstr($host, ':'), 1); $host = substr($host, 0, -1 - strlen($port)); if (!$port) { throw new InvalidArgumentException('Invalid port number'); } } else { $port = 9042; } $this->connection = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($this->connection, getprotobyname('TCP'), 1, 1); socket_set_option($this->connection, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $stream_timeout, "usec" => 0)); if (!socket_connect($this->connection, $host, $port)) { throw new Exception('Unable to connect to Cassandra node: '); } }
/** * Test that HttpSocket::__construct does what one would expect it to do * */ function testConstruct() { $this->Socket->reset(); $baseConfig = $this->Socket->config; $this->Socket->expectNever('connect'); $this->Socket->__construct(array('host' => 'foo-bar')); $baseConfig['host'] = 'foo-bar'; $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']); $this->assertIdentical($this->Socket->config, $baseConfig); $this->Socket->reset(); $baseConfig = $this->Socket->config; $this->Socket->__construct('http://www.cakephp.org:23/'); $baseConfig['host'] = 'www.cakephp.org'; $baseConfig['request']['uri']['host'] = 'www.cakephp.org'; $baseConfig['port'] = 23; $baseConfig['request']['uri']['port'] = 23; $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']); $this->assertIdentical($this->Socket->config, $baseConfig); }
public function __construct($ip, $port = 23, $protocolName = 'tcp') { if (!in_array($protocolName, $this->allowedProtocols)) { $protocolName = 'tcp'; } $this->socket = @socket_create(AF_INET, SOCK_STREAM, getprotobyname($protocolName)); if (!$this->socket) { throw new SocketException('Cannot create socket.'); } $socketSetRcvTimeout = @socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => self::TIMEOUT, 'usec' => 0)); $socketSetSendTimeout = @socket_set_option($this->socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => self::TIMEOUT, 'usec' => 0)); if (!$socketSetRcvTimeout or !$socketSetSendTimeout) { throw new SocketException(socket_strerror(socket_last_error($this->socket))); } $socketConnect = @socket_connect($this->socket, $ip, $port); if (!$socketConnect) { throw new SocketException(socket_strerror(socket_last_error($this->socket))); } }
public function connect() { if ($this->is_connected()) { return true; } if ($this->connection = socket_create($this->socket_domain, SOCK_STREAM, $this->socket_domain > 1 ? getprotobyname('tcp') : 0)) { socket_set_option($this->connection, SOL_SOCKET, SO_REUSEADDR, true); if (socket_bind($this->connection, $this->socket_address, $this->socket_port)) { if (socket_listen($this->connection)) { socket_set_nonblock($this->connection); $this->_open_try = false; // сбрасываем флаг попытки открыть сервер return $this->opened = true; } else { throw new \Exception(socket_strerror(socket_last_error($this->connection))); } } else { $error = socket_last_error($this->connection); socket_clear_error($this->connection); error_log('error: ' . $error); switch ($error) { case SOCKET_EADDRINUSE: // если сокет уже открыт - пробуем его закрыть и снова открыть // @TODO socket close self::socket_close(); // @todo recheck this code // closing socket and try restart $this->disconnect(); if (!$this->_open_try) { $this->_open_try = true; return $this->open(); } break; default: throw new \Exception(socket_strerror($error)); } } } // @TODO delete next line... trigger_error('Server open failed', E_USER_ERROR); return false; }
function Connect($ip = NULL, $porta = NULL) { if ($this->prov) { return false; } //Hack Parametri di default global $config; if ($ip === NULL) { $ip = $config[SHELL][TCP][BIND]; } if ($porta === NULL) { $porta = $config[SHELL][TCP][PORTA]; } $this->prov = 1; $this->coresock = @socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); if (!@socket_connect($this->coresock, $ip, $porta)) { return $this->save_error('Impossibile connettersi al core:' . socket_strerror(socket_last_error()), 1); } $this->connesso = 1; return 1; }
/** * @return resource * @throws \Exception */ public function getConnection($connect_timeout_ms = 10000) { if (!empty($this->socket)) { return $this->socket; } $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or new ConnectionException('Unable to create socket'); socket_set_option($this->socket, getprotobyname('TCP'), TCP_NODELAY, 1); socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, ["sec" => self::STREAM_TIMEOUT, "usec" => 0]); socket_set_option($this->socket, SOL_SOCKET, SO_SNDTIMEO, ["sec" => self::STREAM_TIMEOUT, "usec" => 0]); if (!($this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { throw new ConnectionException("Error Creating Connection to Cassandra: " . socket_strerror(socket_last_error())); } socket_set_nonblock($this->socket); $error = NULL; $attempts = 0; $connected = null; while (!($connected = @socket_connect($this->socket, $this->host, $this->port)) && $attempts++ < $connect_timeout_ms) { $error = socket_last_error(); if ($error == SOCKET_EISCONN) { $connected = true; break; } if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) { socket_close($this->socket); throw new ConnectionException("Error Connecting to '{$this->host}:{$this->port}': " . socket_strerror($error)); } if ($error == 37) { socket_close($this->socket); throw new ConnectionException("Error Connecting to '{$this->host}:{$this->port}': " . socket_strerror($error)); } usleep(1000); } if (!$connected) { socket_close($this->socket); throw new ConnectionException("Error Connecting to '{$this->host}:{$this->port}': Connect Timed Out After {$connect_timeout_ms} seconds."); } socket_set_block($this->socket); return $this->socket; }
/** * 以socket方式开始发送邮件(需要php.ini中设置开启socket的扩展功能)<br/> * @param string $title 邮件主题<br/> * @param string $body 邮件本体的 HTML<br/> * @return boolean 返回布尔值指示是否发送成功<br/><br/> */ public function socket_send($title = null, $body = null) { $this->socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); if (!$this->socket) { $this->show_debug('创建socket失败', true); } if (socket_connect($this->socket, $this->smtp, $this->port)) { $this->show_debug('服务器连接应答:' . $this->safeEncoding(socket_strerror(socket_last_error()))); } else { $this->show_debug('socket连接失败', true); } $this->data = "EHLO HELO\r\n"; $this->do_send(); $this->data = "AUTH LOGIN\r\n"; $this->do_send(); $this->data = base64_encode($this->from) . "\r\n"; $this->do_send(); $this->data = base64_encode($this->pass) . "\r\n"; $this->do_send(); $this->data = "MAIL FROM:<" . $this->from . ">\r\n"; $this->do_send(); $this->data = "RCPT TO:<" . $this->to . ">\r\n"; $this->do_send(); $this->data = "DATA\r\n"; $this->do_send(); $this->data = "MIME-Version:1.0 \r\n"; $this->data .= "Content-type:text/html;charset=utf-8 \r\n"; $this->data .= "From:" . $this->header . "<" . $this->from . ">\r\n"; $this->data .= "To: " . $this->to . "\r\n"; $this->data .= "Subject:" . $this->safeEncoding($title) . "\r\n\r\n"; $this->data .= $this->safeEncoding($body) . "\r\n.\r\n"; $this->do_send(); $this->data = "QUIT\r\n"; $this->do_send(); socket_close($this->socket); return true; }
public function stop() { $address = 'localhost'; $port = 4309; $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_connect($socket, $address, $port); $message = '{"command" : "stop"}' . PHP_EOL; $len = strlen($message); $status = socket_sendto($socket, $message, $len, 0, $address, $port); if ($status !== FALSE) { $message = ''; $next = ''; while ($next = socket_read($socket, 4096)) { $message .= $next; } echo $message; } else { echo "Failed"; } socket_close($socket); // Clean-up the log file // TODO: Il serait bien d'avoir un mécanisme de logs tournants... // unlink('output.log'); }
/** * 建立到服务器的网络连接 * @access protected * @return boolean */ protected function socket() { //创建socket资源 $this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); if (!$this->_socket) { $this->_errorMessage = socket_strerror(socket_last_error()); return false; } socket_set_block($this->_socket); //设置阻塞模式 //连接服务器 if (!socket_connect($this->_socket, $this->_sendServer, $this->_port)) { $this->_errorMessage = socket_strerror(socket_last_error()); return false; } $str = socket_read($this->_socket, 1024); if (!preg_match("/220+?/", $str)) { $this->_errorMessage = $str; return false; } return true; }
/** * Test that HttpSocket::__construct does what one would expect it to do * * @return void */ public function testConstruct() { $this->Socket->reset(); $baseConfig = $this->Socket->config; $this->Socket->expects($this->never())->method('connect'); $this->Socket->__construct(array('host' => 'foo-bar')); $baseConfig['host'] = 'foo-bar'; $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']); $this->assertEquals($this->Socket->config, $baseConfig); $this->Socket->reset(); $baseConfig = $this->Socket->config; $this->Socket->__construct('http://www.cakephp.org:23/'); $baseConfig['host'] = $baseConfig['request']['uri']['host'] = 'www.cakephp.org'; $baseConfig['port'] = $baseConfig['request']['uri']['port'] = 23; $baseConfig['request']['uri']['scheme'] = 'http'; $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']); $this->assertEquals($this->Socket->config, $baseConfig); $this->Socket->reset(); $this->Socket->__construct(array('request' => array('uri' => 'http://www.cakephp.org:23/'))); $this->assertEquals($this->Socket->config, $baseConfig); }
/** * 建立到服务器的网络连接 * @access private * @return boolean */ private function socket() { if (!function_exists("socket_create")) { $this->_errorMessage = "extension php-sockets must be enabled"; return false; } //创建socket资源 $this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); if (!$this->_socket) { $this->_errorMessage = socket_strerror(socket_last_error()); return false; } //连接服务器 if (!socket_connect($this->_socket, $this->_sendServer, $this->_port)) { $this->_errorMessage = socket_strerror(socket_last_error()); return false; } socket_read($this->_socket, 1024); return true; }
public function __construct($address = 'localhost', $port = 80, $callback_on_data_receive = null, $callback_on_hand_shake = null) { pcntl_signal(SIGCHLD, SIG_IGN); ob_implicit_flush(); if ($address == 'localhost') { $this->socket_master = socket_create_listen($port); if ($this->socket_master === false) { echo PHP_EOL . 'WebSocket create_listen failed:' . socket_last_error() . PHP_EOL . PHP_EOL; return false; } socket_set_option($this->socket_master, SOL_SOCKET, SO_REUSEADDR, 1); } else { $this->socket_master = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_set_option($this->socket_master, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($this->socket_master, $address, $port); socket_listen($this->socket_master, 5); // TODO XXX potentially set the 'backlog' parameter } array_push($this->sockets, $this->socket_master); $this->callback_on_data_receive = $callback_on_data_receive; $this->callback_on_hand_shake = $callback_on_hand_shake; echo 'WebSocket Server Active: ' . $address . ':' . $port . PHP_EOL; while (true) { $changed = $this->sockets; $null = null; if (socket_select($changed, $null, $null, null) < 1) { continue; } //if($s == false) echo socket_strerror(socket_last_error()); foreach ($changed as $socket) { if ($socket == $this->socket_master) { $connection = socket_accept($this->socket_master); if ($connection !== false) { if (self::$debug_mode) { $this->debug_msg($connection, 'Connecting'); } $this->connect($connection); } } else { /* $bytes = 0; $buffer = null; while(($recv_bytes = socket_recv($socket, $recv_buffer, 1024, 0)) > 0) { echo rand(1, 9); $bytes += $recv_bytes; $buffer .= $recv_buffer; } */ $bytes = socket_recv($socket, $buffer, 2048, 0); if ($bytes == 0) { if (self::$debug_mode) { $this->debug_msg($socket, 'Disconnecting'); } $this->disconnect($socket); } else { $user = false; foreach ($this->users as &$u) { if ($u->socket == $socket) { $user = $u; break; } } if ($user === false) { continue; } else { if ($user->handshake == false) { $hshake = $this->process_hand_shake($user, $buffer); if ($hshake && $this->callback_on_hand_shake != false && is_callable($this->callback_on_hand_shake)) { $ret = call_user_func($this->callback_on_hand_shake, $user); } } else { if (function_exists('pcntl_fork')) { $id = pcntl_fork(); if ($id == -1) { echo 'forking error'; } else { if ($id) { // parent process continue; } } // child process $this->process_data($user, $buffer); posix_kill(posix_getpid(), SIGINT); } else { $this->process_data($user, $buffer); } } } } } } } }