PHP Method ratchet\ ConnectionInterface::close Code Examples

PHP ratchet\ConnectionInterface::close - 30 examples found. These are the top rated real world PHP examples of method ratchet\ConnectionInterface::close extracted from open source projects. You can rate examples to help us improve the quality of examples
Frequently Used Methods

close() public method

Close the connection
public close ( )
 public function onOpen(WebSocketConnection $connection)
 {
     if (count($this->connections) > 100) {
         $connection->close();
         return;
     }
     $this->connections->pushBack($connection);
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 function onOpen(ConnectionInterface $conn)
 {
     if ($this->isBlocked($conn->remoteAddress)) {
         return $conn->close();
     }
     return $this->_decorating->onOpen($conn);
 }
 public function serve(ConnectionInterface $conn, RequestInterface $request = null, array $parameters)
 {
     try {
         $application = $this->applications->get($parameters['application']);
         $conn->send((string) $application->execute($parameters['module'], $request));
         $conn->close();
     } catch (ApplicationNotFoundException $e) {
         $response = new Response(404, null, $e->getMessage());
         $conn->send((string) $response);
         $conn->close();
     } catch (\Exception $e) {
         $response = new Response(500, null, $e->getMessage());
         $conn->send((string) $response);
         $conn->close();
     }
 }
 function onMessage(ConnectionInterface $from, $msg)
 {
     $msg = explode(' ', $msg);
     $msg[0] = 'pong';
     $from->send(implode(' ', $msg));
     $from->close();
 }
 /**
  * @param \Ratchet\ConnectionInterface $conn
  * @param \Guzzle\Http\Message\RequestInterface $request null is default because PHP won't let me overload; don't pass null!!!
  * @throws \UnexpectedValueException if a RequestInterface is not passed
  */
 public function onOpen(ConnectionInterface $conn, \Guzzle\Http\Message\RequestInterface $request = null)
 {
     $response = new \Guzzle\Http\Message\Response(200);
     $response->setBody(file_get_contents($this->path));
     $conn->send($response);
     $conn->close();
 }
Example #6
0
 /**
  * If we have an error.
  *
  * @param ConnectionInterface $conn
  *
  * @param \Exception $e
  */
 public function onError(ConnectionInterface $conn, \Exception $e)
 {
     /**
      * Close the con on error.
      */
     $conn->close();
 }
Example #7
0
 public function onOpen(ConnectionInterface $from, RequestInterface $request = null)
 {
     if (empty($request)) {
         $resp = new Response(400);
         $from->send((string) $resp);
         $from->close();
         return;
     }
     // Session management
     $saveHandler = $this->_handler;
     $id = $request->getCookie(ini_get('session.name'));
     if (empty($id)) {
         $id = sha1(uniqid() . mt_rand());
     }
     // Crappy workaround for sessions - don't know why they are not saved
     // @see https://github.com/ratchetphp/Ratchet/blob/master/src/Ratchet/Session/SessionProvider.php
     if (isset($this->sessions[$id])) {
         $from->Session = $this->sessions[$id];
     } else {
         $from->Session = new Session(new VirtualSessionStorage($saveHandler, $id, $this->_serializer));
         $this->sessions[$id] = $from->Session;
     }
     if (ini_get('session.auto_start')) {
         $from->Session->start();
     }
     $this->onRequest($from, $request);
 }
Example #8
0
 /**
  * Triggered on connection, populates the connection with a consumer.
  *
  * @param Conn $conn
  *
  * @return TopicsManager
  */
 public function openConnection(Conn $conn)
 {
     try {
         $conn->User = $this->consumerManager->create($conn->Session);
     } catch (\RuntimeException $e) {
         $conn->close();
     }
     return $this;
 }
Example #9
0
 /**
  * @param \Ratchet\ConnectionInterface $conn
  * @param RequestInterface $request null is default because PHP won't let me overload; don't pass null!!!
  * @throws \UnexpectedValueException if a RequestInterface is not passed
  */
 public function onOpen(ConnectionInterface $conn, RequestInterface $request = null)
 {
     if ($this->lastReconnect + Conf::common()['DB']['TIME_TO_RECONNECT'] < time()) {
         $this->lastReconnect = time();
         $this->reconnectDb();
     }
     new HTTP($conn, $request);
     $conn->close();
 }
 public function onOpen(ConnectionInterface $from, RequestInterface $request = null)
 {
     $requestPath = $request->getPath();
     $pathParts = explode('/', preg_replace('#^/peerjs/#', '', $requestPath));
     //Remove /peerjs
     $action = array_pop($pathParts);
     $query = $request->getQuery();
     $peerId = isset($query['id']) ? $query['id'] : null;
     $peerToken = isset($query['token']) ? $query['token'] : null;
     $respStatus = 200;
     $respHeaders = array('Access-Control-Allow-Origin' => '*');
     $respBody = null;
     switch ($action) {
         case 'id':
             $respHeaders['Content-Type'] = 'text/html';
             if ($peerId === null) {
                 do {
                     $peerId = substr(sha1(uniqid('', true) . mt_rand()), 0, self::PEERID_LENGTH);
                 } while ($this->peerServer->peerIdExists($peerId));
             }
             $respBody = $peerId;
             break;
         case 'peers':
             if (self::ALLOW_DISCOVERY) {
                 $peers = $this->peerServer->listPeers();
                 $list = array();
                 foreach ($peers as $peer) {
                     $list[] = $peer['id'];
                 }
                 $respBody = $list;
             } else {
                 $respStatus = 401;
                 // Access denied
             }
             break;
         case 'offer':
         case 'candidate':
         case 'answer':
         case 'leave':
             //TODO: start streaming?
         //TODO: start streaming?
         default:
             $respStatus = 400;
             //Bad request
     }
     if (is_array($respBody)) {
         // Encode to JSON
         $respHeaders['Content-Type'] = 'application/json';
         $respBody = json_encode($respBody);
     }
     //Send response
     $response = new Response($respStatus, $respHeaders, (string) $respBody);
     $from->send((string) $response);
     $from->close();
 }
Example #11
0
 function onOpen(ConnectionInterface $conn)
 {
     if ($this->clients->count() == 4) {
         $conn->send('[8,"system","{\\"error\\":\\"server full, unable to connect\\"}"]');
         $conn->close();
     } else {
         $conn->index = 0;
         $conn->username = '';
         $this->clients->attach($conn);
     }
     echo 'new connection detected.' . PHP_EOL;
 }
Example #12
0
 public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible)
 {
     // If some coolhatsker try to publish a message from the browser console
     if ($conn->remoteAddress !== '127.0.0.1') {
         echo "Illegal publisher from {$conn->remoteAddress} ({$conn->resourceId})\n";
         $conn->close();
         // Kick it!
         return;
     }
     echo "Message to the topic '{$topic}' ({$conn->resourceId})\n";
     //echo var_dump($event);
     // re-send the data to all the clients subscribed to that category
     $topic->broadcast($event);
 }
Example #13
0
 public function serve(ConnectionInterface $conn, RequestInterface $request = null, array $parameters)
 {
     try {
         $path = $this->assets->get($parameters['asset'])->getFullPath();
         if (!file_exists($path)) {
             throw new FileNotFoundException($path);
         }
         $response = new Response(200, array('Content-Type' => Mimetypes::getInstance()->fromFilename($path)), file_get_contents($path));
         $conn->send((string) $response);
         $conn->close();
     } catch (AssetNotFoundException $e) {
         $response = new Response(404, null, '');
         $conn->send((string) $response);
         $conn->close();
     } catch (FileNotFoundException $e) {
         $response = new Response(404, null, '');
         $conn->send((string) $response);
         $conn->close();
     } catch (\Exception $e) {
         $response = new Response(500, null, '');
         $conn->send((string) $response);
         $conn->close();
     }
 }
Example #14
0
 public function onError(ConnectionInterface $con, \Exception $ex)
 {
     // TODO: Log error
     try {
         try {
             if ($this->clients[$con->resourceId]) {
                 $this->clients[$con->resourceId]->endGame();
             }
         } catch (Exception $ex) {
             /* Logic might not exist anymore */
         }
         $con->close();
     } catch (Exception $ex) {
         /* Connection may already be closed */
     }
 }
Example #15
0
 final function onOpen(ConnectionInterface $conn, GuzzleRequest $request = null)
 {
     $this->onRequest($request);
     $userData = $this->session->get('user');
     if (count($userData) == 2 && is_int($userData[0])) {
         $userId = $userData[0];
         $userRole = $userData[1];
         $this->securityProvider->setRole($userData[1]);
         if ($this->securityProvider->isGranted($this->expectedRole)) {
             $actionRequest = new Request($request, $userId);
             $response = call_user_func($this->callback, $actionRequest);
         } else {
             $response = new Response('ACCESS DENIED', Response::HTTP_FORBIDDEN);
         }
         $conn->send((string) $response);
     }
     $conn->close();
 }
 public function onOpen(ConnectionInterface $from, RequestInterface $request = null)
 {
     echo "New HTTP connection!\n";
     //Variables in URLs are not supported in Ratchet for now
     //See https://github.com/cboden/Ratchet/pull/143
     $requestPath = $request->getPath();
     $pathParts = explode('/', preg_replace('#^/peerjs/#', '', $requestPath));
     //Remove /peerjs
     $action = array_pop($pathParts);
     $peerToken = array_pop($pathParts);
     $peerId = array_pop($pathParts);
     $key = array_pop($pathParts);
     $respStatus = 200;
     $respHeaders = array('X-Powered-By' => \Ratchet\VERSION, 'Access-Control-Allow-Origin' => '*');
     $respBody = null;
     switch ($action) {
         case 'id':
             $respHeaders['Content-Type'] = 'text/html';
             if ($peerId === null) {
                 do {
                     $peerId = sha1(uniqid('', true) . mt_rand());
                 } while ($this->peerServer->peerIdExists($peerId));
             }
             $respBody = $peerId;
             break;
         case 'offer':
         case 'candidate':
         case 'answer':
         case 'leave':
             //TODO: start streaming?
         //TODO: start streaming?
         default:
             $respStatus = 400;
             //Bad request
     }
     //Send response
     $response = new Response($respStatus, $respHeaders, (string) $respBody);
     $from->send((string) $response);
     $from->close();
 }
Example #17
0
 /**
  * Close a connection with an HTTP response
  * @param \Ratchet\ConnectionInterface $conn
  * @param int                          $code HTTP status code
  * @return null
  */
 protected function close(ConnectionInterface $conn, $code = 400)
 {
     $response = new Response($code, array('X-Powered-By' => \Ratchet\VERSION));
     $conn->send((string) $response);
     $conn->close();
 }
Example #18
0
 /**
  * @param Ratchet\WebSocket\Version\RFC6455\Connection
  * @param string
  */
 public function onMessage(ConnectionInterface $from, $data)
 {
     $overflow = '';
     if (!isset($from->WebSocket->message)) {
         $from->WebSocket->message = $this->newMessage();
     }
     // There is a frame fragment attached to the connection, add to it
     if (!isset($from->WebSocket->frame)) {
         $from->WebSocket->frame = $this->newFrame();
     }
     $from->WebSocket->frame->addBuffer($data);
     if ($from->WebSocket->frame->isCoalesced()) {
         $frame = $from->WebSocket->frame;
         if (false !== $frame->getRsv1() || false !== $frame->getRsv2() || false !== $frame->getRsv3()) {
             return $from->close($frame::CLOSE_PROTOCOL);
         }
         if (!$frame->isMasked()) {
             return $from->close($frame::CLOSE_PROTOCOL);
         }
         $opcode = $frame->getOpcode();
         if ($opcode > 2) {
             if ($frame->getPayloadLength() > 125 || !$frame->isFinal()) {
                 return $from->close($frame::CLOSE_PROTOCOL);
             }
             switch ($opcode) {
                 case $frame::OP_CLOSE:
                     $closeCode = 0;
                     $bin = $frame->getPayload();
                     if (empty($bin)) {
                         return $from->close();
                     }
                     if (strlen($bin) >= 2) {
                         list($closeCode) = array_merge(unpack('n*', substr($bin, 0, 2)));
                     }
                     if (!$this->isValidCloseCode($closeCode)) {
                         return $from->close($frame::CLOSE_PROTOCOL);
                     }
                     if (!$this->validator->checkEncoding(substr($bin, 2), 'UTF-8')) {
                         return $from->close($frame::CLOSE_BAD_PAYLOAD);
                     }
                     return $from->close($frame);
                     break;
                 case $frame::OP_PING:
                     $from->send($this->newFrame($frame->getPayload(), true, $frame::OP_PONG));
                     break;
                 case $frame::OP_PONG:
                     break;
                 default:
                     return $from->close($frame::CLOSE_PROTOCOL);
                     break;
             }
             $overflow = $from->WebSocket->frame->extractOverflow();
             unset($from->WebSocket->frame, $frame, $opcode);
             if (strlen($overflow) > 0) {
                 $this->onMessage($from, $overflow);
             }
             return;
         }
         $overflow = $from->WebSocket->frame->extractOverflow();
         if ($frame::OP_CONTINUE == $frame->getOpcode() && 0 == count($from->WebSocket->message)) {
             return $from->close($frame::CLOSE_PROTOCOL);
         }
         if (count($from->WebSocket->message) > 0 && $frame::OP_CONTINUE != $frame->getOpcode()) {
             return $from->close($frame::CLOSE_PROTOCOL);
         }
         $from->WebSocket->message->addFrame($from->WebSocket->frame);
         unset($from->WebSocket->frame);
     }
     if ($from->WebSocket->message->isCoalesced()) {
         $parsed = $from->WebSocket->message->getPayload();
         unset($from->WebSocket->message);
         if (!$this->validator->checkEncoding($parsed, 'UTF-8')) {
             return $from->close(Frame::CLOSE_BAD_PAYLOAD);
         }
         $from->WebSocket->coalescedCallback->onMessage($from, $parsed);
     }
     if (strlen($overflow) > 0) {
         $this->onMessage($from, $overflow);
     }
 }
Example #19
0
 /**
  * Close transport
  */
 public function close()
 {
     $this->conn->close();
 }
Example #20
0
 public function onError(ConnectionInterface $conn, \Exception $e)
 {
     unset($conn->handler);
     $conn->close();
 }
Example #21
0
 public function onError(ConnectionInterface $client, \Exception $e)
 {
     echo "Erreur: ({$client->resourceId}) " . $e->getMessage() . PHP_EOL;
     $client->close();
 }
 public function onError(ConnectionInterface $conn, \Exception $e)
 {
     $this->log->debug('Error occurred for user ' . $conn->WebSocket->uid . ': ' . $e->getMessage());
     $conn->close();
 }
Example #23
0
 /**
  * @param ConnectionInterface        $conn
  * @param \Ratchet\Wamp\Topic|string $topic
  * @param string                     $event
  * @param array                      $exclude
  * @param array                      $eligible
  */
 public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible)
 {
     // In this application if clients send data it's because the user hacked around in console
     $conn->close();
 }
 public function onError(ConnectionInterface $connect, \Exception $e)
 {
     echo "An error has occured: " . $e->getMessage() . ".\n";
     $connect->close();
 }
 /**
  * Close a connection with an HTTP response
  * @param Ratchet\ConnectionInterface
  * @param int HTTP status code
  */
 protected function close(ConnectionInterface $conn, $code = 400)
 {
     $response = new Response($code, array('Sec-WebSocket-Version' => $this->versioner->getSupportedVersionString(), 'X-Powered-By' => \Ratchet\VERSION));
     $conn->send((string) $response);
     $conn->close();
 }
Example #26
0
 public function onError(ConnectionInterface $conn, \Exception $e)
 {
     echo "An error has occurred: {$e->getMessage()}\n";
     $conn->close();
 }
Example #27
0
 /**
  * Error handler
  * @param ConnectionInterface $conn
  * @param \Exception $e
  */
 public function onError(ConnectionInterface $conn, \Exception $e)
 {
     $this->logger->error(__METHOD__ . ' | ' . $e->getMessage());
     $conn->close();
 }
Example #28
0
 public function onError(ConnectionInterface $conn, \Exception $e)
 {
     $conn->close();
 }
 /**
  * Função executada quando ocorre algum erro com a conexão
  *
  * @param ConnectionInterface $connection
  * @param \Exception $e
  */
 public function onError(ConnectionInterface $connection, \Exception $e)
 {
     $connection->close();
     Log::d('Ocorreu um erro: ' . $e->getMessage());
 }
Example #30
-1
 public function onOpen(ConnectionInterface $from, RequestInterface $request = null)
 {
     echo "New HTTP connection!\n";
     //Variables in URLs are not supported in Ratchet for now
     //See https://github.com/cboden/Ratchet/pull/143
     $requestPath = $request->getPath();
     $pathParts = explode('/', preg_replace('#^/peerjs/#', '', $requestPath));
     //Remove /peerjs
     $action = array_pop($pathParts);
     $peerToken = array_pop($pathParts);
     $peerId = array_pop($pathParts);
     $key = array_pop($pathParts);
     $respStatus = 200;
     $respHeaders = array('X-Powered-By' => \Ratchet\VERSION, 'Access-Control-Allow-Origin' => '*');
     $respBody = null;
     switch ($action) {
         case 'id':
             $respHeaders['Content-Type'] = 'text/html';
             if ($peerId === null) {
                 do {
                     $peerId = substr(sha1(uniqid('', true) . mt_rand()), 0, self::PEERID_LENGTH);
                 } while ($this->peerServer->peerIdExists($peerId));
             }
             $respBody = $peerId;
             break;
         case 'peers':
             if (self::ALLOW_DISCOVERY) {
                 $peers = $this->peerServer->listPeers();
                 $list = array();
                 foreach ($peers as $peer) {
                     $list[] = $peer['id'];
                 }
                 $respBody = $list;
             } else {
                 $respStatus = 401;
                 // Access denied
             }
             break;
         case 'offer':
         case 'candidate':
         case 'answer':
         case 'leave':
             //TODO: start streaming?
         //TODO: start streaming?
         default:
             $respStatus = 400;
             //Bad request
     }
     if (is_array($respBody)) {
         // Encode to JSON
         $respHeaders['Content-Type'] = 'application/json';
         $respBody = json_encode($respBody);
     }
     //Send response
     $response = new Response($respStatus, $respHeaders, (string) $respBody);
     $from->send((string) $response);
     $from->close();
 }