Example #1
0
 /**
  * @param string $addr
  * @param int $port
  * @return $this
  * @throws Exceptions\SocketException
  */
 public function connect($addr, $port)
 {
     if (!\socket_connect($this->getSocket(), $addr, $port)) {
         throw SocketException::cantConnect($addr, $port);
     }
     return $this;
 }
 /**
  * @param int $maxLoops [default:-1]
  * @param int $usleep [default:100]
  * @throws Exceptions\SocketException
  * @throws \Exception|Exceptions\SocketException
  */
 public function start($maxLoops = -1, $usleep = 100)
 {
     try {
         // onData-callbacks given?
         if (empty($this->onDataCallbacks)) {
             throw SocketException::cantFindCallbacksFor('onData');
         }
         // need to count loops?
         $countLoops = 0 < $maxLoops;
         // start (endless) loop
         $loops = 0;
         while (false === $countLoops || $maxLoops < $loops) {
             // increment loop count if required
             if (true === $countLoops) {
                 ++$loops;
             }
             // accept incoming requests
             $server = $this->connect();
             $client = $server->accept();
             // connection available?
             if ($client && $client instanceof Socket && !isset($this->socketsConnected[$client->getId()])) {
                 // register socket
                 $this->socketsConnected[$client->getId()] = true;
                 // dispatch data to registerd callbacks
                 $handled = false;
                 foreach ($this->onDataCallbacks as $callback) {
                     $handled = \call_user_func($callback, $server, $client);
                     if (true === $handled) {
                         // callback handled request?
                         break;
                     }
                 }
                 // need to close client connection?
                 if (true !== $handled) {
                     $client->close();
                 }
             }
             // sleep some time to prevent system lock
             \usleep((int) $usleep);
             // only keep the last 200 connections
             while (\count($this->socketsConnected) > 200) {
                 \array_shift($this->socketsConnected);
             }
         }
         // close connection
         $this->disconnect();
     } catch (SocketException $e) {
         // close connection
         $this->disconnect();
         // dispatch data to callbacks
         foreach ($this->onErrorCallbacks as $callback) {
             \call_user_func($callback, $e);
         }
         // throw on
         throw $e;
     } catch (\Exception $e) {
         // close connection
         $this->disconnect();
         // throw on
         throw $e;
     }
 }