Esempio n. 1
5
 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);
 }
Esempio n. 2
3
 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);
 }
Esempio n. 3
2
 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);
                 }
             }
         }
     }
 }
 /**
  * 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);
     }
 }
Esempio n. 5
1
 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;
 }
Esempio n. 6
0
 /** @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;
 }
Esempio n. 7
0
 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);
                 }
             }
         }
     }
 }
Esempio n. 8
0
 /**
  * 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;
 }
Esempio n. 9
0
 /**
  * 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();
         }
     }
 }
Esempio n. 10
0
 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);
                 }
             }
         }
     }
 }
Esempio n. 11
0
 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);
                 }
             }
         }
     }
 }
 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();
     }
 }
Esempio n. 13
0
 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));
                     }
                 }
             }
         }
     }
 }
Esempio n. 14
0
 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;
                     }
                 }
             }
         }
     }
 }
Esempio n. 15
0
 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);
 }
Esempio n. 16
0
 /**
  *@name    run
  *@desc    wait for the client to connect and process
  */
 public function run()
 {
     while (true) {
         $socketArr = $this->sockets;
         $write = NULL;
         $except = NULL;
         socket_select($socketArr, $write, $except, NULL);
         //select the socket with message automaticly
         //if handshake choose the master
         foreach ($socketArr 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 {
                 $this->log("----------New Frame Start-------");
                 $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, $buffer);
                     }
                 }
             }
         }
     }
 }
Esempio n. 17
0
 public function select($sec, $usec)
 {
     $read = array($this->sock);
     $write = null;
     $except = null;
     return socket_select($read, $write, $except, $sec, $usec);
 }
Esempio n. 18
0
 public function acceptClients()
 {
     foreach (Events::GetTimedEvents() as $eventIndex => $timedEvent) {
         list($callable, $interval, $lastCall) = $timedEvent;
         if ($lastCall === null) {
             Events::ResetInterval($eventIndex);
         } elseif (time() - $interval < $lastCall) {
             continue;
         } else {
             call_user_func($callable, $this);
             Events::ResetInterval($eventIndex);
         }
     }
     $sockets = array_merge(array($this->masterSocket), $this->sockets);
     $changedSockets = socket_select($sockets, $write, $except, 1);
     if ($changedSockets === 0) {
         return false;
     } else {
         if (in_array($this->masterSocket, $sockets)) {
             $clientSocket = $this->accept();
             $this->handleAccept($clientSocket);
             unset($sockets[0]);
         }
         foreach ($sockets as $socket) {
             $mixedStatus = socket_recv($socket, $buffer, 8192, 0);
             if ($mixedStatus == null) {
                 $this->handleDisconnect($socket);
                 $this->removeClient($socket);
                 continue;
             } else {
                 $this->handleReceive($socket, $buffer);
             }
         }
     }
 }
Esempio n. 19
0
 public function read($length = 1024)
 {
     $data = '';
     while (true) {
         $read = array($this->socket);
         $write = array();
         $except = array();
         $r = socket_select($read, $write, $except, 0, self::TIMEOUT_USEC);
         if (false === $r) {
             throw new PhpBuf_RPC_Socket_Exception('socket select fail: ' . socket_strerror(socket_last_error()));
         }
         if (0 === $r) {
             continue;
         }
         $result = @socket_read($this->socket, $length, PHP_BINARY_READ);
         if (false === $result) {
             throw new PhpBuf_RPC_Socket_Exception('read error:' . socket_strerror(socket_last_error()));
         }
         if (empty($result)) {
             break;
         }
         $data .= $result;
     }
     return $data;
 }
Esempio n. 20
0
 public function socketTick()
 {
     if (!empty($this->readSockets) || !empty($this->writeSockets)) {
         $reads = $this->readSockets;
         $writes = $this->writeSockets;
         $x = [];
         socket_select($reads, $writes, $x, 0);
         if (!empty($writes)) {
             foreach ($writes as $s) {
                 $key = (int) $s;
                 if (isset($this->writeSocketListeners[$key])) {
                     $call = $this->writeSocketListeners[$key];
                     $call();
                 }
             }
         }
         if (!empty($reads)) {
             foreach ($reads as $s) {
                 $key = (int) $s;
                 if (isset($this->readSocketListeners[$key])) {
                     $call = $this->readSocketListeners[$key];
                     $call();
                 }
             }
         }
     }
 }
Esempio n. 21
0
 public function testSocketSelect()
 {
     $this->functions->shouldReceive('socket_select')->once()->with([], null, null, 1, 0)->andReturnUsing(function (&$read) {
         $read = ['(socket1)'];
         return 'call1';
     });
     $this->functions->shouldReceive('socket_select')->once()->with(['(socket1)', '(socket2)', '(socket3)'], null, null, 1, 0)->andReturnUsing(function (&$read, &$write, &$except) {
         $read = ['(socket2)'];
         $write = ['(socket3)'];
         $except = [];
         return 'call2';
     });
     $read = [];
     $write = $except = null;
     $timeout = 1;
     $result = socket_select($read, $write, $except, $timeout);
     $this->assertSame('call1', $result);
     $this->assertSame(['(socket1)'], $read);
     $read = ['(socket1)', '(socket2)', '(socket3)'];
     $write = $except = null;
     $timeout = 1;
     $result = socket_select($read, $write, $except, $timeout);
     $this->assertSame('call2', $result);
     $this->assertSame(['(socket2)'], $read);
     $this->assertSame(['(socket3)'], $write);
     $this->assertSame([], $except);
     $this->assertTrue(true);
 }
Esempio n. 22
0
 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");
     }
     if ($results > 0) {
         foreach ($read_resource_array as $read_resource) {
             if ($this->_listen_socket === $read_resource) {
                 $client_resource = @socket_accept($this->_listen_socket);
                 socket_set_nonblock($client_resource);
                 $this->_socket_array[(int) $client_resource] = $client_resource;
                 $this->_socket_data[(int) $client_resource] = array("client_id" => NULL, "buffer" => "");
             } else {
                 $this->readClient($event_loop, $read_resource);
             }
         }
         foreach ($exception_resource_array as $exception_resource) {
             if ($this->_listen_socket === $read_resource) {
                 throw new Exception("listen socket had exception");
             } else {
                 print "Socket had exception\n";
                 unset($this->_socket_array[(int) $exception_resource]);
                 unset($this->_socket_data[(int) $exception_resource]);
             }
         }
     }
     return TRUE;
 }
 /**
  * Waits for incoming connections.
  */
 public function connect(array $connections, $options)
 {
     $dummy = array();
     $connections[] = $this->sock;
     $ready = @socket_select($connections, $dummy, $dummy, $options['poll_interval']);
     if ($ready === false) {
         throw new StupidHttp_NetworkException("Failed to monitor incoming connections.");
     }
     if ($ready == 0) {
         return null;
     }
     // Check for a new connection.
     $i = array_search($this->sock, $connections);
     if ($i !== false) {
         // Remove our socket from the connections and replace it
         // with the file-descriptor for the new client.
         unset($connections[$i]);
         if (($msgsock = @socket_accept($this->sock)) === false) {
             throw new StupidHttp_NetworkException("Failed accepting connection: " . socket_strerror(socket_last_error($this->sock)));
         }
         if (@socket_set_option($msgsock, SOL_SOCKET, SO_REUSEADDR, 1) === false) {
             throw new StupidHttp_NetworkException("Failed setting address re-use option: " . socket_strerror(socket_last_error($msgsock)));
         }
         $timeout = array('sec' => $options['timeout'], 'usec' => 0);
         if (@socket_set_option($msgsock, SOL_SOCKET, SO_RCVTIMEO, $timeout) === false) {
             throw new StupidHttp_NetworkException("Failed setting timeout value: " . socket_strerror(socket_last_error($msgsock)));
         }
         $connections[] = $msgsock;
     }
     return $connections;
 }
 private function mainLoop()
 {
     $changed_sockets = $this->allsockets;
     @socket_select($changed_sockets, $write = null, $exceptions = null, 0);
     foreach ($this->apps as $app) {
         $app->onTick();
     }
     foreach ($changed_sockets as $socket) {
         if ($socket == $this->master) {
             if (($rec = socket_accept($this->master)) < 0) {
                 $this->log("Error: Could not connect\n" . socket_strerror(socket_last_error($rec)));
                 continue;
             } else {
                 $this->log("New client connecting...");
                 $client = new Connection($this, $rec);
                 $this->clients[$rec] = $client;
                 $this->allsockets[] = $rec;
             }
         } else {
             $client = $this->clients[$socket];
             $bytes = @socket_recv($socket, $data, 4096, 0);
             if (!$bytes) {
                 $client->onDisconnect();
                 unset($this->clients[$socket]);
                 $index = array_search($socket, $this->allsockets);
                 unset($this->allsockets[$index]);
                 unset($client);
             } else {
                 $client->onData($data);
             }
         }
     }
 }
Esempio n. 25
0
 private function _read($sock, $len, $timeout)
 {
     $data = '';
     $size = 0;
     while ($size < $len) {
         $r = array($sock);
         $w = array();
         $e = array();
         $n = socket_select($r, $w, $e, $timeout);
         if ($n === false) {
             throw new Bert_Rpc_Error_ConnectionError($this->_svc->host, $this->_svc->port, socket_strerror(socket_last_error()));
         } elseif ($n === 0) {
             throw new Bert_Rpc_Error_ReadTimeoutError($this->_svc->host, $this->_svc->port, $this->_svc->timeout);
         }
         $bytes = socket_recvfrom($sock, $msg, $len - $size, 0, $name, $port);
         if ($bytes === false) {
             throw new Bert_Rpc_Error_ConnectionError($this->_svc->host, $this->_svc->port, socket_strerror(socket_last_error()));
         } elseif ($bytes === 0) {
             throw new Bert_Rpc_Error_ReadError($this->_svc->host, $this->_svc->port);
         }
         $size += $bytes;
         $data .= $msg;
     }
     return $data;
 }
Esempio n. 26
0
 public function socketSelect(array $fd_read = array($this->fsock), array $fd_write = array($this->fsock))
 {
     $ret = socket_select($fd_read, $fd_write, $except = NULL, $this->connect_timeout, 0);
     if ($ret != 1) {
         throw new Exception("socket select fail", 5004);
     }
     return $this;
 }
Esempio n. 27
0
 public function index()
 {
     $array1 = C("MODULE_ALLOW_LIST");
     //echo var_dump(stream_get_transports());
     //echo $_SERVER['HTTP_HOST'] . $_SERVER['SERVER_PORT'] . "<br />";
     /*        $fp = fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']);
             if (!$fp) {
                 echo "wrong";
             }
             else {
                 $out = "GET /Home/Index/index?id=5 HTTP/1.1\r\n";
                 $out .= "Host: localhost\r\n";
                 $out .= "Connection: Close\r\n\r\n";
                 echo $out . "<br />";
                 fwrite($fp, $out);
                 while (!feof($fp)) {
                     echo fgets($fp, 128);
                 }
                 fclose($fp);
             }*/
     //phpinfo();
     $host = I('server.HTTP_HOST');
     $port = 9050;
     echo $host . " " . I('server.SERVER_PORT') . "\n";
     // create a streaming socket, of type TCP/IP
     $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     echo $sock . "\n";
     // set the option to reuse the port
     socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, TRUE);
     // "bind" the socket to the address to "localhost", on port $port
     // so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc.
     socket_bind($sock, $host, $port);
     // start listen for connections
     socket_listen($sock);
     // create a list of all the clients that will be connected to us..
     // add the listening socket to this list
     $clients = array($sock);
     //$this->master = $server;
     //$this->sockets[] = $this->master;
     echo 111;
     socket_select($this->sockets, $write, $except, NULL);
     // while(true) {
     /*$changes = $this->sockets;
     
                 socket_select($this->sockets, $write, $except, NULL);
     
                 foreach($changes as $sock) {
                     if ($sock == $server) {
                         $client = socket_accept($this->master);
                         echo $client;
                         $this->users = array(
                             'socket'=>$client,
                             'shou'=>false
                         );
                     }
                 }*/
     // }
 }
Esempio n. 28
-1
 public static function connect($cb)
 {
     $null = NULL;
     while (true) {
         $changed = self::$clients;
         @socket_select($changed, $null, $null, 1);
         if (in_array(self::$socket, $changed)) {
             $socket = socket_accept(self::$socket);
             self::$clients[] = $socket;
             // read data form client
             self::parseHeader(socket_read($socket, 1024));
             // setResponse socket
             self::setResponse($socket);
             socket_getpeername($socket, $ip);
             $found_socket = array_search(self::$socket, $changed);
             unset($changed[$found_socket]);
         }
         // loop all socket connection
         foreach ($changed as $client) {
             while (socket_recv($client, $buf, 2048, 0) > 0) {
                 call_user_func($cb, json_decode(self::unmask($buf), true));
                 break 2;
             }
             $buf = @socket_read($client, 1024, PHP_NORMAL_READ);
             if ($buf == false) {
                 $found_socket = array_search($client, self::$clients);
                 socket_getpeername($client, $ip);
                 unset(self::$clients[$found_socket]);
             }
         }
     }
 }
Esempio n. 29
-1
function recvall($length, $timeout = 5)
{
    global $s;
    $endtime = time() + $timeout;
    $rdata = "";
    $remain = $length;
    while ($remain > 0) {
        $rtime = $endtime - $timeout;
        if ($rtime < 0) {
            return null;
        }
        $e = NULL;
        $r = array($s);
        @socket_select($r, $w, $e, 5);
        if (in_array($s, $r)) {
            $d = @socket_recv($s, $data, $remain, 0);
            if (false == $data) {
                return null;
            }
            $rdata .= $data;
            $remain -= strlen($data);
        }
    }
    return $rdata;
}
 function begin()
 {
     while (true) {
         $changed = $this->sockets;
         try {
             socket_select($changed, $write = NULL, $except = NULL, NULL);
         } catch (exception $e) {
             echo "Socket Closed";
         }
         foreach ($changed as $socket) {
             if ($socket == $this->master) {
                 $client = socket_accept($socket);
                 if ($client < 0 || $client === false) {
                     console("socket_accept() failed");
                     continue;
                 } else {
                     $this->connect($client);
                 }
             } else {
                 $bytes = @socket_recv($socket, $buffer, 2048, 0);
                 $this->console(bin2hex($buffer));
                 if ($bytes == 0) {
                     $this->disconnect($socket);
                 } else {
                     $user = $this->getuserbysocket($socket);
                     if (!$user->handshake) {
                         $this->dohandshake($user, $buffer);
                     } else {
                         $this->process($user, $buffer);
                     }
                 }
             }
         }
     }
 }