Esempio n. 1
29
 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();
 }
Esempio n. 2
11
 /**
  * Dispatches an event for the called RPC
  *
  * @param \Ratchet\ConnectionInterface $conn
  * @param string $id
  * @param string|\Ratchet\Wamp\Topic $topic
  * @param array $params
  */
 public function onCall(Conn $conn, $id, $topic, array $params)
 {
     $topicName = self::getTopicName($topic);
     $eventPayload = ['connection' => $conn, 'id' => $id, 'connectionData' => $this->_connections[$conn->WAMP->sessionId]];
     $event = $this->dispatchEvent('Rachet.WampServer.Rpc', $this, array_merge($eventPayload, ['topicName' => $topicName, 'topic' => $topic, 'params' => $params, 'wampServer' => $this]));
     if ($event->isStopped()) {
         $conn->callError($id, $event->result['stop_reason']['error_uri'], $event->result['stop_reason']['desc'], $event->result['stop_reason']['details']);
         $this->outVerbose('Rachet.WampServer.Rpc.' . $topicName . ' call (' . $id . ') was blocked');
         $this->dispatchEvent('Rachet.WampServer.RpcBlocked', $this, array_merge($eventPayload, ['topicName' => $topicName, 'reason' => $event->result['stop_reason']]));
         return false;
     }
     $start = microtime(true);
     $deferred = new \React\Promise\Deferred();
     $deferred->promise()->then(function ($results) use($conn, $id, $topicName, $start, $eventPayload) {
         $end = microtime(true);
         $conn->callResult($id, $results);
         $this->outVerbose('Rachet.WampServer.Rpc.' . $topicName . ' call (' . $id . ') took <info>' . ($end - $start) . 's</info> and succeeded');
         $this->dispatchEvent('Rachet.WampServer.RpcSuccess', $this, array_merge($eventPayload, ['topicName' => $topicName, 'results' => $results]));
     }, function ($errorUri, $desc = '', $details = null) use($conn, $id, $topicName, $start, $eventPayload) {
         $end = microtime(true);
         $conn->callError($id, $errorUri, $desc, $details);
         $this->outVerbose('Rachet.WampServer.Rpc.' . $topicName . ' call (' . $id . ') took <info>' . ($end - $start) . 's</info> and failed');
         $this->dispatchEvent('Rachet.WampServer.RpcFailed', $this, array_merge($eventPayload, ['topicName' => $topicName, 'reason' => [$errorUri, $desc, $details]]));
     });
     $this->dispatchEvent('Rachet.WampServer.Rpc.' . $topicName, $this, array_merge($eventPayload, ['promise' => $deferred, 'topic' => $topic, 'params' => $params, 'wampServer' => $this]));
 }
Esempio n. 3
10
 public function dispatch(Conn $conn, $id, $topic, array $params)
 {
     $parts = explode("/", $topic->getId());
     if (count($parts) < 2) {
         $conn->callError($id, $topic, "Incorrectly formatted Topic name", array("topic_name" => $topic->getId()));
         return;
     }
     $handler = $this->getHandler($parts[0]);
     $method = $this->toCamelCase($parts[1]);
     $result = null;
     if ($handler) {
         try {
             $result = call_user_func(array($handler, $method), $conn, $params);
         } catch (\Exception $e) {
             $conn->callError($id, $topic, $e->getMessage(), array("code" => $e->getCode(), "rpc" => $topic->getId(), "params" => $params));
             return;
         }
         if ($result === null) {
             //incase handler doesnt return anything!
             $result = false;
         }
     }
     if ($result) {
         if (!is_array($result)) {
             $result = array($result);
         }
         $conn->callResult($id, $result);
         return;
     } elseif ($result === false) {
         $conn->callError($id, $topic, "RPC Failed", array("rpc" => $topic->getId(), "params" => $params));
     }
     $conn->callError($id, $topic, "Unable to find that command", array("rpc" => $topic->getId(), "params" => $params));
     return;
 }
Esempio n. 4
7
 /**
  * @param ConnectionInterface $conn
  * @param string              $id
  * @param string              $topic
  * @param WampRequest         $request
  * @param array               $params
  */
 public function dispatch(ConnectionInterface $conn, $id, $topic, WampRequest $request, array $params)
 {
     $callback = $request->getRoute()->getCallback();
     try {
         $procedure = $this->rpcRegistry->getRpc($callback);
     } catch (\Exception $e) {
         $conn->callError($id, $topic, $e->getMessage(), ['rpc' => $topic, 'request' => $request]);
         return;
     }
     $method = $this->toCamelCase($request->getAttributes()->get('method'));
     $result = null;
     try {
         $result = call_user_func([$procedure, $method], $conn, $request, $params);
     } catch (\Exception $e) {
         $conn->callError($id, $topic, $e->getMessage(), ['code' => $e->getCode(), 'rpc' => $topic, 'params' => $params, 'request' => $request]);
         return;
     }
     if ($result === null) {
         $result = false;
     }
     if ($result) {
         if ($result instanceof RpcResponse) {
             $result = $result->getData();
         } elseif (!is_array($result)) {
             $result = [$result];
         }
         $conn->callResult($id, $result);
         return;
     } elseif ($result === false) {
         $conn->callError($id, $topic, 'RPC Error', ['rpc' => $topic, 'params' => $params, 'request' => $request]);
     }
     $conn->callError($id, $topic, 'Unable to find that command', ['rpc' => $topic->getId(), 'params' => $params, 'request' => $request]);
     return;
 }
Esempio n. 5
7
 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();
 }
 /**
  * @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();
 }
 public function onCall(ConnectionInterface $conn, $id, $topic, array $params)
 {
     switch ($topic->getId()) {
         case "synchronize":
             $conn->callResult($id, $this->playerData);
             break;
         default:
             $conn->callError($id, $topic, 'You are not allowed to make calls')->close();
     }
     // In this application if clients send data it's because the user hacked around in console
 }
Esempio n. 8
5
 public function onMessage(ConnectionInterface $from, $msg)
 {
     $from->send($msg);
     $now = date(DATE_RFC2822);
     $headers = $from->WebSocket->request->getHeader('User-Agent');
     echo "{$now} -- id:{$from->resourceId} -- {$from->remoteAddress} -- {$headers} -- ({$msg})\n";
 }
 public function onOpen(WebSocketConnection $connection)
 {
     if (count($this->connections) > 100) {
         $connection->close();
         return;
     }
     $this->connections->pushBack($connection);
 }
Esempio n. 10
5
 /**
  * Triggered when a client sends data through the socket
  * @param  \Ratchet\ConnectionInterface $from The socket/connection that sent the message to your application
  * @param  string $msg The message received
  * @throws \Exception
  */
 function onMessage(ConnectionInterface $from, $msg)
 {
     echo $_SESSION["city"];
     if ($msg == "update") {
         $from->send(updateMessage());
     } else {
         parse_request($msg);
     }
 }
Esempio n. 11
5
 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 */
     }
 }
 function onMessage(ConnectionInterface $from, $msg)
 {
     $msg = explode(' ', $msg);
     $msg[0] = 'pong';
     $from->send(implode(' ', $msg));
     $from->close();
 }
Esempio n. 13
3
 /**
  * {@inheritdoc}
  */
 function onOpen(ConnectionInterface $conn)
 {
     if ($this->isBlocked($conn->remoteAddress)) {
         return $conn->close();
     }
     return $this->_decorating->onOpen($conn);
 }
Esempio n. 14
3
 /**
  * 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();
 }
Esempio n. 15
3
File: Game.php Progetto: rdbn/gnome
 public function onCall(ConnectionInterface $conn, $id, $topic, array $params)
 {
     $roomId = $topic->getId();
     if (!array_key_exists($roomId, $this->rooms)) {
         $this->rooms[$roomId] = new \SplObjectStorage();
     }
     return $conn->callResult($id, array('id' => $roomId, 'display' => $topic));
 }
 /**
  * Triggered when a client sends data through the socket
  * @param  \Ratchet\ConnectionInterface $from The socket/connection that sent the message to your application
  * @param  string $message The message received
  * @throws \Exception
  */
 function onMessage(ConnectionInterface $from, $message)
 {
     $json = json_decode($message, true, 2);
     $ticket = $json['ticket'];
     $method = $json['method'];
     $requestContent = $json['request'];
     // Dispatch request.
     $server = ['REQUEST_METHOD' => $method, 'REQUEST_URI' => '/data/', 'SERVER_PORT' => 843, 'HTTP_HOST' => 'localhost:843', 'HTTP_ACCEPT' => 'application/json'];
     $request = new Request([], [], [], [], [], $server, $requestContent);
     $response = $this->kernel->handle($request);
     // Send back response.
     $websocketData = json_encode(['ticket' => $ticket, 'status' => $response->getStatusCode(), 'response' => $response->getContent()]);
     $from->send($websocketData);
 }
Esempio n. 17
2
 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);
 }
Esempio n. 18
2
 /**
  * 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;
 }
 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();
 }
Esempio n. 20
1
 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);
 }
Esempio n. 21
0
 public function dumpChatBacklog(ConnectionInterface $conn, $msgobj)
 {
     $session = $msgobj->session;
     $messages = \orm\Message::findBySession($session);
     for ($index = 0; $index < sizeof($messages); $index++) {
         $data = array("cmdType" => "message", "timestamp" => $messages[$index]->getTimestamp(), "text" => $messages[$index]->getText(), "user" => $messages[$index]->getUser());
         $conn->send(json_encode($data));
     }
 }
Esempio n. 22
0
 /**
  * HTTP constructor.
  * @param \Ratchet\ConnectionInterface $conn
  * @param RequestInterface $request
  */
 public function __construct(ConnectionInterface $conn, RequestInterface $request)
 {
     /** @var \GuzzleHttp\Psr7\Request $request */
     $this->request = $request;
     $class = __NAMESPACE__ . '\\controllers\\' . str_replace('/', '', $request->getUri()->getPath());
     $controller = new $class($this);
     /** @var Controller $controller */
     $controller->main();
     $conn->send($controller->getHeaders()->getString(strlen($controller->getOutput())) . $controller->getOutput());
 }
Esempio n. 23
0
 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();
 }
Esempio n. 24
0
 public function onError(ConnectionInterface $conn, \Exception $e)
 {
     require_once 'propel-config.php';
     $con = Propel::getConnection('pos');
     $con->rollBack();
     $this->log("Client {$conn->resourceId} hit an error: {$e->getMessage()} in {$e->getFile()} on line {$e->getLine()}");
     $data['success'] = false;
     $data['errmsg'] = $e->getMessage();
     $results['event'] = $conn->event;
     $results['data'] = $data;
     $conn->send(json_encode($results));
 }
Esempio n. 25
0
 public function onMessage(ConnectionInterface $from, $message)
 {
     if ($message === 'exit') {
         exit;
     }
     if ($message === 'Dump headers') {
         $from->send($from->WebSocket->request->getRawHeaders());
     } elseif ($auth = $from->WebSocket->request->getHeader('Authorization')) {
         $from->send("{$auth} - {$message}");
     } else {
         $from->send($message);
     }
 }
 /**
  * Tests that requests from clients are sent back as responses
  */
 public function testMessageHandling()
 {
     $authenticationRequest = new AuthenticationRequest($this->configuration->getAccessToken());
     // Authenticate the client
     $this->_manager->handleMessage($authenticationRequest, $this->_clientMock);
     $expectedResponse = new AuthenticationResponse(AuthenticationResponse::STATUS_SUCCESS);
     $this->_clientMock->expects($this->once())->method('send')->with(json_encode($expectedResponse));
     $this->_manager->onMessage($this->_clientMock, json_encode($authenticationRequest));
 }
Esempio n. 27
-1
 public function ping($timeout = 10)
 {
     $payload = $this->pingSeq;
     $this->conn->send(new Frame($payload, true, Frame::OP_PING));
     $seq = $this->pingSeq;
     $this->pingSeq++;
     if ($timeout > 0) {
         $timer = $this->loop->addTimer($timeout, function () use($seq) {
             if (isset($this->pingRequests[$seq])) {
                 $this->pingRequests[$seq]['deferred']->reject('timeout');
                 unset($this->pingRequests[$seq]);
             }
         });
         $deferred = new Deferred();
         $this->pingRequests[$seq] = array('seq' => $seq, 'deferred' => $deferred, 'timer' => $timer);
         return $deferred->promise();
     }
 }
Esempio n. 28
-2
 /**
  * Envia a mensagem para uma conexão
  *
  * @param Message $message
  * @param ConnectionInterface $connection
  */
 public static function send($message, $connection)
 {
     if (!is_string($message)) {
         $message = json_encode($message);
     }
     $connection->send($message);
 }
Esempio n. 29
-2
 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;
 }
Esempio n. 30
-3
 /**
  * @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();
 }