当前位置: 首页>>代码示例>>PHP>>正文


PHP socket_select函数代码示例

本文整理汇总了PHP中socket_select函数的典型用法代码示例。如果您正苦于以下问题:PHP socket_select函数的具体用法?PHP socket_select怎么用?PHP socket_select使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了socket_select函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: run

 public function run()
 {
     $null = NULL;
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
     socket_bind($socket, $this->host, $this->port);
     socket_listen($socket);
     socket_set_nonblock($socket);
     $this->clients = array($socket);
     //start endless loop
     while (true) {
         $changed = $this->clients;
         socket_select($changed, $null, $null, 0, 10);
         //check for new socket
         if (in_array($socket, $changed)) {
             if (($socket_new = socket_accept($socket)) !== false) {
                 $this->clients[] = $socket_new;
                 $header = socket_read($socket_new, 1024);
                 if ($this->handshake($header, $socket_new) === false) {
                     continue;
                 }
                 socket_getpeername($socket_new, $ip);
                 if (isset($this->events['open'])) {
                     $this->events['open']($this, $ip);
                 }
                 $found_socket = array_search($socket, $changed);
                 unset($changed[$found_socket]);
             }
         }
         //loop through all connected sockets
         foreach ($changed as $changed_socket) {
             //check for any incomming data
             while (socket_recv($changed_socket, $buf, 1024, 0) >= 1) {
                 $received_text = $this->unmask($buf);
                 //unmask data
                 $data = json_decode($received_text, true);
                 //json decode
                 if (isset($this->events['message'])) {
                     $this->events['message']($this, $data);
                 }
                 break 2;
             }
             $buf = socket_read($changed_socket, 1024, PHP_NORMAL_READ);
             // check disconnected client
             if ($buf === false) {
                 $found_socket = array_search($changed_socket, $this->clients);
                 socket_getpeername($changed_socket, $ip);
                 unset($this->clients[$found_socket]);
                 if (isset($this->events['close'])) {
                     $this->events['close']($this, $ip);
                 }
             }
         }
         if ($this->timeout) {
             sleep($this->timeout);
         }
     }
     socket_close($socket);
 }
开发者ID:nicklasos,项目名称:websockets,代码行数:59,代码来源:WebSocket.php

示例2: start

 public function start()
 {
     $host = $this->host;
     $port = $this->port;
     echo "app can be acessed from ws://{$host}:{$port}\n";
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($socket === false) {
         $this->logLastError($socket, "1");
     }
     if (socket_bind($socket, $host, $port) === false) {
         $this->logLastError($socket, "2");
     }
     if (socket_listen($socket, 5) === false) {
         $this->logLastError($socket, "3");
     }
     $this->setServerSocket($socket);
     $serverSocket = $this->getServerSocket();
     do {
         $sockets = $this->getSockets();
         //Set up a blocking call to socket_select
         $write = null;
         $except = null;
         $tv_sec = 5;
         if (socket_select($sockets, $write, $except, $tv_sec) < 1) {
             continue;
         } else {
             $this->setSockets($sockets);
         }
         //Handle new Connections
         if ($this->hasSocket($serverSocket)) {
             $clientSocket = socket_accept($serverSocket);
             if ($clientSocket === false) {
                 $this->logLastError($serverSocket, "4");
             } else {
                 $this->setClientSocket($clientSocket);
                 $response = "HTTP/1.1 101 Switching Protocols";
                 $this->respond($clientSocket, $response);
             }
         }
         //Handle Input
         foreach ($this->getClientSockets() as $clientSocket) {
             if ($this->hasSocket($clientSocket)) {
                 $message = socket_read($clientSocket, 2048, PHP_NORMAL_READ);
                 if ($message === false) {
                     $this->logLastError($clientSocket, "5");
                     $this->removeSocket($clientSocket);
                     socket_close($clientSocket);
                     break;
                 } else {
                     $message = trim($message);
                     if (!empty($message)) {
                         $response = $this->trigger("message", ["{$message}"]);
                         $this->respond($clientSocket, $response);
                     }
                 }
             }
         }
     } while (true);
     socket_close($serverSocket);
 }
开发者ID:wispira,项目名称:framework,代码行数:60,代码来源:Server.php

示例3: run

 public function run()
 {
     while (true) {
         $changed_sockets = $this->allsockets;
         @socket_select($changed_sockets, $write = NULL, $exceptions = NULL, NULL);
         foreach ($changed_sockets as $socket) {
             if ($socket == $this->master) {
                 if (($ressource = socket_accept($this->master)) < 0) {
                     $this->log('Socket error: ' . socket_strerror(socket_last_error($ressource)));
                     continue;
                 } else {
                     $client = new Connection($this, $ressource);
                     $this->clients[$ressource] = $client;
                     $this->allsockets[] = $ressource;
                 }
             } else {
                 $client = $this->clients[$socket];
                 $bytes = @socket_recv($socket, $data, 4096, 0);
                 if ($bytes === 0) {
                     $client->onDisconnect();
                     unset($this->clients[$socket]);
                     $index = array_search($socket, $this->allsockets);
                     unset($this->allsockets[$index]);
                     unset($client);
                 } else {
                     $client->onData($data);
                 }
             }
         }
     }
 }
开发者ID:kiwina6969,项目名称:php-websocket,代码行数:31,代码来源:Server.php

示例4: connect

 /**
  * 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);
     }
 }
开发者ID:heartless-gaming,项目名称:game-server-status,代码行数:43,代码来源:TCPSocket.php

示例5: process

 public function process(LooPHP_EventLoop $event_loop, $timeout)
 {
     $read_resource_array = $this->_socket_array;
     $write_resource_array = NULL;
     $exception_resource_array = $this->_socket_array;
     $results = socket_select($read_resource_array, $write_resource_array, $exception_resource_array, is_null($timeout) ? NULL : floor($timeout), is_null($timeout) ? NULL : fmod($timeout, 1) * 1000000);
     if ($results === FALSE) {
         throw new Exception("stream_select failed");
     } else {
         if ($results > 0) {
             foreach ($read_resource_array as $read_resource) {
                 if ($this->_listen_socket === $read_resource) {
                     $client_resource = @socket_accept($this->_listen_socket);
                     $this->_socket_array[(int) $client_resource] = $client_resource;
                 } else {
                     //send http responce in 5 second (just to demo events)
                     $event_loop->addEvent(function () use($read_resource) {
                         $send_data = "HTTP/1.0 200 OK\n" . "Content-Type: text/html\n" . "Server: LooPHP" . "\r\n\r\n" . "<body>Hello World</body>";
                         socket_write($read_resource, $send_data);
                         socket_close($read_resource);
                     }, 5);
                     unset($this->_socket_array[(int) $read_resource]);
                 }
             }
             foreach ($exception_resource_array as $exception_resource) {
                 print "Socket had exception\n";
                 unset($this->_socket_array[(int) $exception_resource]);
             }
         }
     }
     return TRUE;
 }
开发者ID:Wordi,项目名称:LooPHP,代码行数:32,代码来源:sockets.php

示例6: poll

 /** @return false if there is nothing to poll */
 static function poll($timeout = 2)
 {
     if (!count(self::$sockets)) {
         return false;
     }
     if (self::$nextPing) {
         $timeout = min(max(0.1, self::$nextPing - microtime(true)), $timeout);
     }
     // break early, to ping
     $queuecopy = self::$sockets;
     $null = NULL;
     if (!($res = socket_select($queuecopy, $null, $null, floor($timeout), ceil($timeout * 1000000)))) {
         if ($res === false) {
             throw new ExAsyncSocket("select() failure: " . socket_strerror(socket_last_error()));
         }
         usleep(8000);
         //d("Nothing changed during select()");
         return true;
     }
     foreach ($queuecopy as $sock) {
         //d("$sock Socket read!");
         if (!isset(self::$handlers["{$sock}"])) {
             continue;
         }
         // might have unregistered in the meantime!
         $handler = self::$handlers["{$sock}"];
         $handler->read();
     }
     self::$nextPing = microtime(true) + 4;
     foreach (self::$handlers as $id => $handler) {
         $handler->ping();
     }
     return true;
 }
开发者ID:bitemyapp,项目名称:Sblam,代码行数:35,代码来源:asyncsocket.php

示例7: run

 function run()
 {
     while (true) {
         $changes = $this->sockets;
         socket_select($changes, $write = NULL, $except = NULL, NULL);
         foreach ($changes as $sock) {
             if ($sock == $this->master) {
                 $client = socket_accept($this->master);
                 //$key=uniqid();
                 $this->sockets[] = $client;
                 $this->users[] = array('socket' => $client, 'shou' => false);
             } else {
                 $len = socket_recv($sock, $buffer, 2048, 0);
                 $k = $this->search($sock);
                 if ($len < 7) {
                     $name = $this->users[$k]['ming'];
                     $this->close($sock);
                     $this->send2($name, $k);
                     continue;
                 }
                 if (!$this->users[$k]['shou']) {
                     $this->woshou($k, $buffer);
                 } else {
                     $buffer = $this->uncode($buffer);
                     $this->send($k, $buffer);
                 }
             }
         }
     }
 }
开发者ID:heroazure,项目名称:learning,代码行数:30,代码来源:demo.php

示例8: process

 /**
  * Socket processing iteration:
  * accepting client connections,
  * processing client messages
  */
 public function process()
 {
     $numChanged = socket_select($this->_read, $empty, $empty, 0, 10);
     if ($numChanged) {
         if (in_array($this->_serverSocket, $this->_read)) {
             if (count($this->_clientSockets) < $this->_maxClients) {
                 $this->_clientSockets[] = socket_accept($this->_serverSocket);
             }
         }
         foreach ($this->_clientSockets as $key => $client) {
             if (in_array($client, $this->_read)) {
                 $input = socket_read($client, 1024);
                 if ($input === false) {
                     socket_shutdown($client);
                     unset($this->_clientSockets[$key]);
                 } else {
                     if ($input && false !== ($MessageContainer = unserialize($input))) {
                         foreach ($this->_listeners as $Listener) {
                             $Listener->receive($MessageContainer->getMessage());
                         }
                     }
                     socket_close($client);
                     unset($this->_clientSockets[$key]);
                 }
             }
         }
     }
     $this->_read = $this->_clientSockets;
     $this->_read[] = $this->_serverSocket;
 }
开发者ID:jack-po,项目名称:php-multiprocessing,代码行数:35,代码来源:Server.php

示例9: start

 /**
  * start the server
  *
  */
 public function start()
 {
     $this->startDaemonSocket();
     if ($this->idleTimeout !== null) {
         $idleLast = time();
     }
     while (true) {
         $watchedSockets = array();
         array_push($watchedSockets, $this->daemonSocket);
         foreach ($this->clients as $socket) {
             array_push($watchedSockets, $socket->getSocket());
         }
         $ready = @socket_select($watchedSockets, $this->null, $this->null, $this->idleTimeout);
         if ($ready === false) {
             $this->dieExit('Socket_select failed:' . $this->getLastSocketErrorMessage());
         }
         if ($ready == 0 && $this->idleTimeout !== null && $idleLast + $this->idleTimeout <= time()) {
             $idleLast = time();
             $this->debug('Calling onIdle() handler.');
             $this->listener->onIdle();
             continue;
         }
         if (in_array($this->daemonSocket, $watchedSockets)) {
             $this->acceptConnection();
         }
         foreach ($watchedSockets as $socket) {
             if ($socket == $this->daemonSocket) {
                 continue;
             }
             $this->socket = $this->clients[$socket];
             $this->handleRequest();
         }
     }
 }
开发者ID:AmineCherrai,项目名称:rostanvo,代码行数:38,代码来源:Sequential.class.php

示例10: serviceRequest

 function serviceRequest()
 {
     while (true) {
         $readFDs = array($this->clientFD[0]);
         //    block and wait for data
         $ready = @socket_select($readFDs, $this->null, $this->null, null);
         // the auto-request of favicon.ico gives things fits, so null check
         if ($ready === false && $this->clientFD[0] && socket_last_error($this->clientFD[0]) !== 0) {
             $this->_sendDebugMessage('socket_select() failed.');
             $this->shutdown();
         }
         if (in_array($this->clientFD[0], $readFDs) && !$ready === false) {
             $data = $this->readFromSocket();
             // empty data => connection was closed
             if ($data === false) {
                 $this->_sendDebugMessage('Connection closed by peer');
                 $this->closeConnection();
             } else {
                 $this->_sendDebugMessage('Received ' . trim($data) . ' from ' . $this->_getDebugInfo());
                 if (method_exists($this->callbackObj, 'onReceiveData')) {
                     $this->callbackObj->onReceiveData(0, $data);
                 }
             }
         }
     }
 }
开发者ID:horus-by,项目名称:php-webdriver,代码行数:26,代码来源:LocalWebServer.php

示例11: run

 function run()
 {
     while (true) {
         $sockets = $this->sockets;
         $write = NULL;
         $except = NULL;
         socket_select($sockets, $write, $except, NULL);
         foreach ($sockets as $sock) {
             if ($sock == $this->master) {
                 $client = socket_accept($this->master);
                 $this->sockets[] = $client;
                 $this->users[] = array('socket' => $client, 'handShake' => false);
             } else {
                 $len = socket_recv($sock, $buffer, 2048, 0);
                 $k = $this->search($sock);
                 if ($len < 7) {
                     $this->close($sock);
                     continue;
                 }
                 if (!$this->users[$k]['handShake']) {
                     $this->handShake($k, $buffer);
                 } else {
                     $buffer = $this->uncode($buffer);
                     $this->send($k, $buffer);
                 }
             }
         }
     }
 }
开发者ID:vvvui,项目名称:vvvui.github.com,代码行数:29,代码来源:socket.php

示例12: run

 public function run()
 {
     $done = false;
     $startTime = microtime(true);
     while (!$done) {
         $readSockets = $writeSockets = array();
         /**
          * @var $client SquidPurgeClient
          */
         foreach ($this->clients as $clientIndex => $client) {
             $sockets = $client->getReadSocketsForSelect();
             foreach ($sockets as $i => $socket) {
                 $readSockets["{$clientIndex}/{$i}"] = $socket;
             }
             $sockets = $client->getWriteSocketsForSelect();
             foreach ($sockets as $i => $socket) {
                 $writeSockets["{$clientIndex}/{$i}"] = $socket;
             }
         }
         if (!count($readSockets) && !count($writeSockets)) {
             break;
         }
         $exceptSockets = null;
         $timeout = min($startTime + $this->timeout - microtime(true), 1);
         MediaWiki\suppressWarnings();
         $numReady = socket_select($readSockets, $writeSockets, $exceptSockets, $timeout);
         MediaWiki\restoreWarnings();
         if ($numReady === false) {
             wfDebugLog('squid', __METHOD__ . ': Error in stream_select: ' . socket_strerror(socket_last_error()) . "\n");
             break;
         }
         // Check for timeout, use 1% tolerance since we aimed at having socket_select()
         // exit at precisely the overall timeout
         if (microtime(true) - $startTime > $this->timeout * 0.99) {
             wfDebugLog('squid', __CLASS__ . ": timeout ({$this->timeout}s)\n");
             break;
         } elseif (!$numReady) {
             continue;
         }
         foreach ($readSockets as $key => $socket) {
             list($clientIndex, ) = explode('/', $key);
             $client = $this->clients[$clientIndex];
             $client->doReads();
         }
         foreach ($writeSockets as $key => $socket) {
             list($clientIndex, ) = explode('/', $key);
             $client = $this->clients[$clientIndex];
             $client->doWrites();
         }
         $done = true;
         foreach ($this->clients as $client) {
             if (!$client->isIdle()) {
                 $done = false;
             }
         }
     }
     foreach ($this->clients as $client) {
         $client->close();
     }
 }
开发者ID:Acidburn0zzz,项目名称:mediawiki,代码行数:60,代码来源:SquidPurgeClientPool.php

示例13: listen

 function listen()
 {
     while (true) {
         $changed = $this->sockets;
         socket_select($changed, $write = NULL, $except = NULL, NULL);
         foreach ($changed as $socket) {
             if ($socket == $this->master) {
                 $client = socket_accept($this->master);
                 if ($client < 0) {
                     $this->log("socket_accept() failed");
                     continue;
                 } else {
                     $this->connect($client);
                 }
             } else {
                 $bytes = @socket_recv($socket, $buffer, 2048, 0);
                 if ($bytes == 0) {
                     $this->disconnect($socket);
                 } else {
                     $user = $this->getuserbysocket($socket);
                     if (!$user->handshake) {
                         $this->dohandshake($user, $buffer);
                     } else {
                         $this->process($user, $this->unwrap($buffer));
                     }
                 }
             }
         }
     }
 }
开发者ID:GeorgeNava,项目名称:phpwebsocket,代码行数:30,代码来源:websocket.class.php

示例14: run

 public function run()
 {
     $null = NULL;
     while (true) {
         $changed = $this->allClients;
         socket_select($changed, $null, $null, 0, 10);
         foreach ($this->socketServers as $socketServer) {
             $socket = $socketServer->socket;
             if (in_array($socket, $changed)) {
                 $newSocket = socket_accept($socket);
                 $this->allClients[] = $newSocket;
                 $socketServer->clients[] = $newSocket;
                 $socketServer->newConnect($newSocket);
                 $foundSocket = array_search($socket, $changed);
                 unset($changed[$foundSocket]);
             }
         }
         foreach ($changed as $changedSocket) {
             foreach ($this->socketServers as $socketServer) {
                 if (in_array($changedSocket, $socketServer->clients)) {
                     switch ($socketServer->socketChanged($changedSocket)) {
                         case AbstractSocketServer::$INCOMING_DATA:
                             break 2;
                         case AbstractSocketServer::$LOSE_CONNECT:
                             $foundSocket = array_search($changedSocket, $this->allClients);
                             unset($this->allClients[$foundSocket]);
                             break;
                     }
                 }
             }
         }
     }
 }
开发者ID:WeishengChang,项目名称:wogap,代码行数:33,代码来源:SocketCenter.class.php

示例15: __construct

 public function __construct($host, $port)
 {
     $this->host = $host;
     $this->port = $port;
     $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
     socket_bind($sock, 0, $this->port);
     socket_listen($sock);
     $clients = array($sock);
     while (true) {
         $read = $clients;
         if (socket_select($read, $write = null, $except = null, 0) < 1) {
             continue;
         }
         if (in_array($sock, $read)) {
             $clients[] = $newSocket = socket_accept($sock);
             $this->handShake($newSocket);
             socket_getpeername($newSocket, $ip);
             $this->send(array('type' => 'system', 'message' => $ip . ' Connected'), $clients);
             echo "New client connected: {$ip}\n";
             $key = array_search($sock, $read);
             unset($read[$key]);
         }
         foreach ($read as $read_sock) {
             while (socket_recv($read_sock, $buf, 1024, 0) >= 1) {
                 $msg = json_decode($this->unmask($buf), true);
                 $this->send($msg, $clients);
             }
         }
     }
     socket_close($sock);
 }
开发者ID:jakubpas,项目名称:websocket,代码行数:32,代码来源:Server.php


注:本文中的socket_select函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。