/** * Connects the TCP socket to the host with the given IP address and port * number * * Depending on whether PHP's sockets extension is loaded, this uses either * <var>socket_create</var>/<var>socket_connect</var> or * <var>fsockopen</var>. * * @param string $ipAddress The IP address to connect to * @param int $portNumber The TCP port to connect to * @param int $timeout The timeout in milliseconds * @throws SocketException if an error occurs during connecting the socket */ public function connect($ipAddress, $portNumber, $timeout) { $this->ipAddress = $ipAddress; $this->portNumber = $portNumber; if ($this->socketsEnabled) { if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { throw new SocketException(socket_last_error($this->socket)); } socket_set_nonblock($this->socket); @socket_connect($this->socket, $ipAddress, $portNumber); $write = array($this->socket); $read = $except = array(); $sec = floor($timeout / 1000); $usec = $timeout % 1000; if (!socket_select($read, $write, $except, $sec, $usec)) { $errorCode = socket_last_error($this->socket); } else { $errorCode = socket_get_option($this->socket, SOL_SOCKET, SO_ERROR); } if ($errorCode) { throw new SocketException($errorCode); } socket_set_block($this->socket); } else { if (!($this->socket = @fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, $timeout / 1000))) { throw new SocketException($socketErrstr); } stream_set_blocking($this->socket, true); } }
function PHPSconnect($adress, $password, $port = 11223) { $this->socket = socket_create(AF_INET, SOCK_STREAM, 0); socket_set_block($this->socket); $result = socket_connect($this->socket, $adress, $port); if ($this->socket == null) { return 1; } socket_write($this->socket, sha1($password) . "\n", strlen(sha1($password)) + 2); //auth $result = recv($this->socket); if ($result == "PHPSpass0") { return 0; } else { if ($result == "PHPSpass1") { return 2; } else { if ($result == "PHPSpass2") { return 3; } else { if ($result == "PHPSbusy") { return 4; } else { return 5; } } } } }
public function start() { //确保在连接客户端时不会超时 echo "1"; set_time_limit(0); $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() 建立失败的原因是:" . socket_strerror(socket_last_error()) . "/n"); //阻塞模式 echo "2"; socket_set_block($this->socket) or die("socket_set_block() 阻塞失败的原因是:" . socket_strerror(socket_last_error()) . "/n"); //绑定到socket端口 echo "3"; $result = socket_bind($this->socket, $this->address, 5062) or die("socket_bind() 绑定失败的原因是:" . socket_strerror(socket_last_error()) . "/n"); //开始监听 echo "4"; $result = socket_listen($this->socket, 4) or die("socket_listen() 监听失败的原因是:" . socket_strerror(socket_last_error()) . "/n"); echo "Begin listining"; do { // never stop the daemon //它接收连接请求并调用一个子连接Socket来处理客户端和服务器间的信息 $msgsock = socket_accept($this->socket) or die("socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "/n"); //读取客户端数据 echo "Read client data \n"; //socket_read函数会一直读取客户端数据,直到遇见\n,\t或者\0字符.PHP脚本把这写字符看做是输入的结束符. $buf = socket_read($msgsock, 21000); echo "Received msg: {$buf} \n"; //数据传送 向客户端写入返回结果 $msg = "welcome \n"; socket_write($msgsock, $msg, strlen($msg)) or die("socket_write() failed: reason: " . socket_strerror(socket_last_error()) . "/n"); //一旦输出被返回到客户端,父/子socket都应通过socket_close($msgsock)函数来终止 socket_close($msgsock); } while (true); socket_close($this->socket); }
/** * 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; }
/** * Create server * - bind to port * - listen port * @throws ListenException * @throws BindException */ function create($blocking = true) { $this->open(); $serverSocket = $this->getSocketResource(); if (!socket_bind($serverSocket, $this->getIp(), $this->getPort())) { throw new BindException($this); } $this->getEventDispatcher()->dispatch(BindEvent::getEventName(), new BindEvent($this, $this)); if (!socket_listen($serverSocket)) { throw new ListenException($this); } if ($blocking) { socket_set_block($serverSocket); } else { socket_set_nonblock($serverSocket); } $this->start(); while ($this->running) { $clientSocket = socket_accept($serverSocket); if (false == $clientSocket) { continue; } $socket = new Socket($this->getAddressType(), $this->getSocketType(), $this->getTransport(), $this->getEventDispatcher()); $socket->setSocketResource($clientSocket); $socket->getEventDispatcher()->dispatch(NewConnectionEvent::getEventName(), new NewConnectionEvent($socket, $this)); } }
private function _openConnection($debug = null) { $connection = false; if (function_exists('socket_create') && function_exists('socket_connect') && function_exists('socket_strerror') && function_exists('socket_last_error') && function_exists('socket_set_block') && function_exists('socket_read') && function_exists('socket_write') && function_exists('socket_close')) { $this->_sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($this->_sock, SOL_SOCKET, SO_RCVTIMEO, ['sec' => 5, 'usec' => 0]); socket_set_option($this->_sock, SOL_SOCKET, SO_SNDTIMEO, ['sec' => 5, 'usec' => 0]); @($connection = socket_connect($this->_sock, $this->_serverIP, $this->_serverRconQueryPort)); if ($debug == '-d') { echo '[DEBUG]: ' . socket_strerror(socket_last_error()) . ".\n"; } if ($connection) { socket_set_block($this->_sock); } $this->_sockType = 1; } else { if (function_exists('fsockopen')) { if ($debug == '-d') { @($this->_sock = fsockopen('tcp://' . $this->_serverIP, $this->_serverRconQueryPort, $errno, $errstr, 10)); if (!$this->_sock) { echo '[DEBUG]: ' . $errno . ' - ' . $errstr . "\n"; } } else { @($this->_sock = fsockopen('tcp://' . $this->_serverIP, $this->_serverRconQueryPort)); } $connection = $this->_sock; $this->_sockType = 2; } } return $connection; }
/** * Create a Socket Server on the given domain and port * @param $domain String * @param $port Float[optional] */ function create($domain, $port = 9801) { $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($this->socket, $domain, $port); socket_listen($this->socket); socket_set_block($this->socket); }
protected function handleRequest($conn) { socket_set_block($conn); $request = ''; $bytes = socket_recv($conn, $request, 16384, 0); if ($bytes === false) { L::level(L::DEBUG) && L::log(L::DEBUG, __CLASS__, "Problem reading from socket: %s", array(socket_last_error($conn))); return; } $request = explode("\n", $request); $get_line = explode(' ', $request[0]); if (preg_match('#^/nowplaying\\.json(?:\\?.*|$)#', $get_line[1])) { $data = array(); if (isset($this->most_recent_track)) { $track = $this->most_recent_track; $data = array('artist' => $track->getArtist(), 'title' => $track->getTitle(), 'album' => $track->getAlbum(), 'length' => $track->getLengthInSeconds()); } $body = json_encode($data); $len = strlen($body); $lines = array('HTTP/1.0 200 OK', 'Date: ' . date('r'), 'Content-Type: application/json', 'Content-Length: ' . $len, 'Server: ScratchLive! Scrobbler', 'Connection: close', '', $body); socket_write($conn, implode("\n", $lines)); socket_close($conn); L::level(L::DEBUG) && L::log(L::DEBUG, __CLASS__, "Finished handling request.", array()); } else { $body = '<html><head><title>404 Not Found</title></head><body>No Dice.</body></html>'; $len = strlen($body); $lines = array('HTTP/1.0 404 Not Found', 'Date: ' . date('r'), 'Content-Type: text/html', 'Content-Length: ' . $len, 'Server: ScratchLive! Scrobbler', 'Connection: close', '', $body); socket_write($conn, implode("\n", $lines)); socket_close($conn); L::level(L::DEBUG) && L::log(L::DEBUG, __CLASS__, "Handled unknown request.", array()); } }
function getsock($port) { $socket = null; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false || $socket === null) { $error = socket_strerror(socket_last_error()); $msg = "socket create({$port}) failed"; echo "ERR: {$msg} '{$error}'\n"; return NULL; } socket_set_nonblock($socket); $res = socket_connect($socket, API_HOST, $port); $timeout = 50; while ($res === false && $timeout > 0) { $err = socket_last_error($socket); echo "."; if ($timeout > 1 && ($err == 115 || $err == 114)) { $timeout--; usleep(50); $res = socket_connect($socket, API_HOST, $port); continue; } $error = socket_strerror($err); $msg = "socket connect({$port}) failed"; echo "ERR: {$msg} '{$error}'\n"; socket_close($socket); return NULL; } socket_set_block($socket); return $socket; }
public function __construct(Server $server, $password, $port = 19132, $interface = "0.0.0.0", $threads = 1, $clientsPerThread = 50) { $this->server = $server; $this->workers = []; $this->password = (string) $password; $this->server->getLogger()->info("Starting remote control listener"); if ($this->password === "") { $this->server->getLogger()->critical("RCON can't be started: Empty password"); return; } $this->threads = (int) max(1, $threads); $this->clientsPerThread = (int) max(1, $clientsPerThread); $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->socket === false or !socket_bind($this->socket, $interface, (int) $port) or !socket_listen($this->socket)) { $this->server->getLogger()->critical("RCON can't be started: " . socket_strerror(socket_last_error())); $this->threads = 0; return; } socket_set_block($this->socket); for ($n = 0; $n < $this->threads; ++$n) { $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread); } socket_getsockname($this->socket, $addr, $port); $this->server->getLogger()->info("RCON running on {$addr}:{$port}"); }
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"); } } }
/** * Connects the TCP socket to the host with the given IP address and port number */ public function connect(InetAddress $ipAddress, $portNumber) { $this->ipAddress = $ipAddress; $this->portNumber = $portNumber; if ($this->socketsEnabled) { if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { $errorCode = socket_last_error($this->socket); throw new Exception("Could not create socket: " . socket_strerror($errorCode)); } if (@(!socket_connect($this->socket, $ipAddress, $portNumber))) { $errorCode = socket_last_error($this->socket); throw new Exception("Could not connect socket: " . socket_strerror($errorCode)); } if ($this->isBlocking) { socket_set_block($this->socket); } else { socket_set_nonblock($this->socket); } } else { if (!($this->socket = fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, 2))) { throw new Exception("Could not create socket."); } stream_set_blocking($this->socket, $this->isBlocking); } }
public function check($ip, $port, $timeout = 2) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_nonblock($sock); socket_connect($sock, $ip, $port); socket_set_block($sock); self::$status = socket_select($r = array($sock), $w = array($sock), $f = array($sock), 2); return self::$status; }
public function CloseConnections() { foreach ($this->servers as $server) { $arrOpt = array('l_onoff' => 1, 'l_linger' => 1); socket_set_block($server); socket_set_option($server, SOL_SOCKET, SO_LINGER, $arrOpt); socket_close($server); } }
public static function Block($block) { if ($block === true) { // Block socket type socket_set_block(self::$Socket); } else { // Non block socket type socket_set_nonblock(self::$Socket); } }
public function check($ip, $port) { if (!isset(self::$status[$ip])) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_nonblock($sock); socket_connect($sock, $ip, $port); socket_set_block($sock); self::$status[$ip] = socket_select($r = array($sock), $w = array($sock), $f = array($sock), 1); } }
function _getsock($fun, $port, $tmo, $unix = true) { $socket = null; if ($unix === true) { $socket = socket_create(AF_UNIX, SOCK_STREAM, 0); } else { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } if ($socket === false || $socket === null) { $sle = socket_last_error(); $sockerr = socket_strerror($sle); $msg = "{$fun}() _getsock() create({$port}) failed"; error_log("CKPERR: {$msg} ({$sle}) '{$sockerr}'"); return false; } if ($unix === true) { $res = socket_connect($socket, $port, NULL); } else { $res = socket_connect($socket, '127.0.0.1', $port); } if ($res === false) { // try 3x if ($unix === true) { $res = socket_connect($socket, $port); } else { sleep(2); $res = socket_connect($socket, '127.0.0.1', $port); } if ($res === false) { if ($unix === true) { $res = socket_connect($socket, $port); } else { sleep(5); $res = socket_connect($socket, '127.0.0.1', $port); } if ($res === false) { $sle = socket_last_error(); $sockerr = socket_strerror($sle); if ($unix === true) { $msg = "{$fun}() _getsock() connect({$port}) failed 3x"; } else { $msg = "{$fun}() _getsock() connect({$port}) failed 3x (+2+5s sleep)"; } error_log("CKPERR: {$msg} ({$sle}) '{$sockerr}'"); socket_close($socket); return false; } } } # Avoid getting locked up for long socktmo($socket, $tmo); # Enable timeout socket_set_block($socket); return $socket; }
function fork_buffer() { global $parent_sock, $buffer, $connected; socket_write($parent_sock, "buffer\n"); if (strlen($buffer) < 128 and $connected) { socket_set_block($parent_sock); } else { socket_set_nonblock($parent_sock); } return urldecode(trim(socket_read($parent_sock, 4096, PHP_NORMAL_READ))); }
public function CloseConnections() { foreach ($this->clients as $client) { $arrOpt = array('l_onoff' => 1, 'l_linger' => 1); socket_set_block($client); socket_set_option($client, SOL_SOCKET, SO_LINGER, $arrOpt); socket_close($client); } $arrOpt = array('l_onoff' => 1, 'l_linger' => 1); socket_set_block($this->socket); socket_set_option($this->socket, SOL_SOCKET, SO_LINGER, $arrOpt); socket_close($this->socket); }
public function __construct($host, $port, $timeout) { $this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($this->sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0)); socket_set_option($this->sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => $timeout, 'usec' => 0)); if (!socket_connect($this->sock, $host, $port)) { $errno = socket_last_error($this->sock); $errstr = socket_strerror($errno); throw new \Exception("Error Connecting to server({$errno}): {$errstr} "); } socket_set_block($this->sock); socket_set_option($this->sock, SOL_TCP, TCP_NODELAY, 1); }
public function testOnClose() { $this->app->expects($this->once())->method('onClose')->with($this->isInstanceOf('\\Ratchet\\ConnectionInterface')); $client = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($client, SOL_SOCKET, SO_REUSEADDR, 1); socket_set_option($client, SOL_SOCKET, SO_SNDBUF, 4096); socket_set_block($client); socket_connect($client, 'localhost', $this->port); $this->server->loop->tick(); socket_shutdown($client, 1); socket_shutdown($client, 0); socket_close($client); $this->server->loop->tick(); }
public function testOnClose() { $client = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($client, SOL_SOCKET, SO_REUSEADDR, 1); socket_set_option($client, SOL_SOCKET, SO_SNDBUF, 4096); socket_set_block($client); socket_connect($client, 'localhost', $this->port); $this->server->loop->tick(); socket_shutdown($client, 1); socket_shutdown($client, 0); socket_close($client); $this->server->loop->tick(); usleep(5000); $this->assertSame($this->app->last['onOpen'][0], $this->app->last['onClose'][0]); }
public function socket() { /** * 服务器端代码 */ //确保在连接客户端时不会超时 set_time_limit(0); //设置IP和端口号 $address = "localhost"; $port = 1935; //创建一个SOCKET if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) { echo "socket_create() failed: reason:" . socket_strerror(socket_last_error()) . "\n"; die; } //阻塞模式 if (socket_set_block($sock) == false) { echo "socket_set_block() failed: reason:" . socket_strerror(socket_last_error()) . "\n"; die; } //绑定到socket端口 if (socket_bind($sock, $address, $port) == false) { echo "socket_bind() failed: reason:" . socket_strerror(socket_last_error()) . "\n"; die; } //开始监听 if (socket_listen($sock, 4) == false) { echo "socket_listen() failed: reason:" . socket_strerror(socket_last_error()) . "\n"; die; } do { if (($msgsock = socket_accept($sock)) === false) { echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "\n"; die; } //发到客户端 $msg = "welcome \n"; if (socket_write($msgsock, $msg, strlen($msg)) === false) { echo "socket_write() failed: reason: " . socket_strerror(socket_last_error()) . "\n"; die; } echo iconv("UTF-8", "GB2312", "读取客户端发来的信息\n"); $buf = socket_read($msgsock, 8192); echo iconv("UTF-8", "GB2312", "收到的信息: {$buf} \n"); socket_close($msgsock); } while (true); socket_close($sock); }
/** Write text to server via TCP socket @param $print_server [string] host or host:port @param $text [string] text to print @return - [int] 1 => success - [int] 0 => problem sending text - [int] -1 => sent but no response. printer might be stuck/blocked */ public static function printToServer($printer_server, $text) { $port = 9450; if (strstr($printer_server, ':')) { list($printer_server, $port) = explode(':', $printer_server, 2); } if (!function_exists('socket_create')) { return 0; } $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { return 0; } socket_set_block($socket); socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 2, 'usec' => 0)); if (!socket_connect($socket, $printer_server, $port)) { return false; } $send_failed = false; while (true) { $num_written = socket_write($socket, $text); if ($num_written === false) { // error occurred $send_failed = true; break; } if ($num_written >= strlen($text)) { // whole message has been sent // send ETX to signal message complete socket_write($socket, chr(0x3)); break; } else { $text = substr($text, $num_written); } } $ack = socket_read($socket, 3); socket_close($socket); if ($send_failed) { return 0; } else { if ($ack === false) { return -1; } else { return 1; } } }
private function SetBlock($block) { if (!$this->inited) { return $this->inited; } $result = true; if ($block) { $result = socket_set_block($this->socket); } else { $result = socket_set_nonblock($this->socket); } if (!$result) { $this->lastError = "SetMode() failed reason: " . socket_strerror(socket_last_error()); } return $result; }
public static function connect($host='localhost', $port=9000) { self::$socket = socket_create(AF_INET, SOCK_STREAM, 0); if (self::$socket) { if (socket_connect(self::$socket, $host, $port)) { socket_set_block(self::$socket); self::$connected = true; } else { $err = socket_strerror(socket_last_error(self::$socket)); throw new DebugClientError('Cannot connect to Debugger server! Reason: '.$err); } } else { throw new DebugClientError('Cannot initialize socket!'); } }
/** * Sets up the socket connection * * @throws \Exception */ public function connect() { $this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($this->sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $this->timeout, 'usec' => 0)); socket_set_option($this->sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => $this->timeout, 'usec' => 0)); if (!socket_connect($this->sock, $this->host, $this->port)) { $errno = socket_last_error($this->sock); $errstr = socket_strerror($errno); throw new AMQPIOException(sprintf('Error Connecting to server (%s): %s', $errno, $errstr), $errno); } socket_set_block($this->sock); socket_set_option($this->sock, SOL_TCP, TCP_NODELAY, 1); if ($this->keepalive) { $this->enable_keepalive(); } }
function check_port($host, $port, $timeout, $force_fsock = false) { if (function_exists('socket_create') && !$force_fsock) { // Create a TCP/IP socket. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket == false) { return false; } // if (socket_set_nonblock($socket) == false) { socket_close($socket); return false; } // @socket_connect($socket, $host, $port); // will return FALSE as it's async, so no check // if (socket_set_block($socket) == false) { socket_close($socket); return false; } switch (socket_select($r = array($socket), $w = array($socket), $f = array($socket), $timeout)) { case 2: // Refused $result = false; break; case 1: $result = true; break; case 0: // Timeout $result = false; break; } // cleanup socket_close($socket); } else { $socket = @fsockopen($host, $port, $errno, $errstr, 5); if (!$socket) { $result = false; } else { $result = true; @fclose($socket); } } return $result; }
function test($stream, $sock) { if ($stream !== null) { echo "stream_set_blocking "; print_r(stream_set_blocking($stream, 0)); echo "\n"; } if ($sock !== null) { echo "socket_set_block "; print_r(socket_set_block($sock)); echo "\n"; echo "socket_get_option "; print_r(socket_get_option($sock, SOL_SOCKET, SO_TYPE)); echo "\n"; } echo "\n"; }
function create_socket($uri, $block = false) { $set = parse_url($uri); if ($uri[0] == 'u') { $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); } else { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } if ($block) { socket_set_block($sock); } else { socket_set_nonblock($sock); } socket_bind($sock, $set['host'], $set['port']); socket_listen($sock); return $socket; }