send() public method

Send data to the connection
public send ( string $data ) : Ratchet\ConnectionInterface
$data string
return Ratchet\ConnectionInterface
Ejemplo 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();
 }
Ejemplo n.º 2
21
 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();
     }
 }
Ejemplo n.º 3
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();
 }
Ejemplo n.º 5
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";
 }
Ejemplo n.º 6
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);
     }
 }
Ejemplo n.º 7
4
 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();
 }
 public function onMessage(ConnectionInterface $from, $msg)
 {
     //echo("[" . date('m/d/Y H:i:s') . "] $msg\r\n");
     $returns = handleControllerData($msg);
     $id = count($returns) - 2;
     $stopSame = $returns[$id];
     unset($returns[$id]);
     if ($returns != NULL && $returns != "") {
         foreach ($this->clients as $client) {
             if (!$stopSame) {
                 $client->send(json_encode($returns, JSON_FORCE_OBJECT));
             } else {
                 if ($stopSame == 1) {
                     if ($from !== $client) {
                         $client->send(json_encode($returns, JSON_FORCE_OBJECT));
                     }
                 } else {
                     if ($stopSame == 2) {
                         // special case to send back variable from the recipient
                         $from->send(json_encode($returns, JSON_FORCE_OBJECT));
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 10
3
 private function eventconnect(ConnectionInterface $from, $data)
 {
     $avatar = 'http://api.adorable.io/avatars/150/' . rand(100000, 999999) . '.png';
     $this->clients[$from->resourceId]['avatar'] = $avatar;
     $this->clients[$from->resourceId]['is_admin'] = $data->is_admin;
     $send_data = ['event' => 'connect', 'clients' => $this->clients];
     $from->send(json_encode(['event' => 'connected', 'avatar' => $avatar]));
     $this->sendMessageToAll($send_data);
 }
 /**
  * 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);
 }
Ejemplo n.º 12
2
 public function onMessage(ConnectionInterface $from, $msg)
 {
     $message = json_decode($msg);
     if (isset($message)) {
         echo $message->command . "(" . $from->resourceId . ") > ";
         if ($message->command == "read") {
             echo "reading data ... \n";
             $from->testObject->success = true;
             $from->send(json_encode($from->testObject));
         }
         if ($message->command == "create") {
             echo "set data ...\n";
             $from->testObject = $message->data;
             // someting like update in db
             //$globalTestObject = $message->data;
             $from->testObject->success = true;
             $from->send(json_encode($message->data));
         }
     }
     /* its send to all clients recived message
             $numRecv = count($this->clients) - 1;
     
             echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
                 , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
     
             foreach ($this->clients as $client) {
                 if ($from !== $client) {
                     // The sender is not the receiver, send to each client connected
                     $client->send($msg);
                 }
             }
             */
 }
Ejemplo n.º 13
2
 public function onMessage(ConnectionInterface $from, $msg)
 {
     if ($this->mpd->checkConnection()) {
         $this->mpdState = true;
     } else {
         $this->mpdState = false;
         $this->mpdConnect();
     }
     if ($this->mpdState) {
         $msg = json_decode($msg);
         switch ($msg->type) {
             case 'echo':
                 $from->send(json_encode(['value' => $msg->value, 'callback' => $msg->callback]));
                 break;
             case 'mpdCommand':
                 if ($this->mpdState) {
                     $value = $this->mpd->writeCommand($msg->command);
                     $from->send(json_encode(['value' => $value, 'callback' => $msg->callback]));
                 } else {
                     $from->send(json_encode(['value' => '', 'callback' => $msg->callback]));
                 }
                 break;
         }
     }
 }
Ejemplo n.º 14
2
 public function onMessage(ConnectionInterface $from, $msg)
 {
     $datas = json_decode($msg, true);
     /**
      * We must check if the token is sent
      * If there is no token, we cant log the player
      * and link him to the current game.
      */
     if (!isset($datas['type'])) {
         $from->send('Invalid or inaccessible type');
         return;
     }
     if ($datas['']) {
     } else {
         if ($datas['']) {
         }
     }
     echo "Recieving new message : {$msg} from {$from->resourceId}.\n";
     foreach ($this->clients as $client) {
         if ($from !== $client) {
             // The sender is not the receiver, send to each client connected
             $client->send(json_encode($datas, true));
         }
     }
 }
Ejemplo n.º 15
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);
 }
Ejemplo n.º 16
2
 public function onOpen(ConnectionInterface $conn)
 {
     $username = $conn->WebSocket->request->getQuery()->get('username');
     // Store the new connection to send messages to later
     $this->clients[$conn->resourceId] = $conn;
     $conn->send(json_encode(['type' => 'welcome']));
     echo "New connection! ({$conn->resourceId})\n";
     $this->updateClientLists();
 }
Ejemplo n.º 17
1
 public function onMessage(ConnectionInterface $from, $json)
 {
     $data = json_decode($json);
     if (!isset($data->id) || !isset($data->action)) {
         $from->send(json_encode(array('status' => 'error', 'message' => 'Invalid values.')));
         return;
     }
     switch ($data->action) {
         case "join":
             foreach ($this->clients as $client) {
                 if ($from == $client) {
                     $from->send(json_encode(array('status' => 'error', 'message' => 'You already joined to any.')));
                     return;
                 }
             }
             if (!isset($this->rooms[$data->id])) {
                 $this->rooms[$data->id] = new \SplObjectStorage();
             }
             $this->rooms[$data->id]->attach($from);
             $this->clients->attach($from);
             $from->send(json_encode(array('status' => 'success')));
             break;
         case "post":
             foreach ($this->rooms as $id => $storage) {
                 if ($storage->contains($from) && $id === $data->id) {
                     foreach ($storage as $client) {
                         if ($from != $client) {
                             $client->send($json);
                         }
                     }
                     $from->send(json_encode(array('status' => 'success')));
                     break;
                 }
             }
             $from->send(json_encode(array('status' => 'error', 'message' => 'Invalid values.')));
             break;
         default:
             $from->send(json_encode(array('status' => 'error', 'message' => 'Invalid action.')));
             break;
     }
 }
Ejemplo n.º 18
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);
     }
 }
Ejemplo n.º 19
0
 /**
  * Send a message to a connection
  * 
  * @param string $msg
  * @param ConnectionInterface $to
  */
 protected function send($msg, ConnectionInterface $to)
 {
     if (is_array($msg)) {
         $msg = json_encode($msg);
     }
     $to->send($msg);
 }
Ejemplo n.º 20
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));
     }
 }
Ejemplo n.º 21
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());
 }
Ejemplo n.º 22
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();
 }
Ejemplo n.º 23
0
 public function onMessage(ConnectionInterface $connection, $messageAsJson)
 {
     $message = json_decode($messageAsJson, true);
     $this->debug('Income message: ' . var_export($message, true));
     if (!isset($message['event']) || !isset($this->handlers[$message['event']])) {
         $response = ['event' => 'unknownEvent', 'data' => null, 'error' => 'event ' . @$message['event'] . ' not described'];
         $this->debug('Send message: ' . var_export($response, true));
         $connection->send(json_encode($response));
         return;
     }
     /** @var Handler\HandlerInterface $handler */
     $handler = $this->serviceLocator->get($this->handlers[$message['event']]);
     if (!$handler instanceof Handler\HandlerInterface) {
         $response = ['event' => 'unknownEvent', 'data' => null, 'error' => 'handler for event ' . $message['event'] . ' must be instance of T4web\\Websocket\\Handler\\HandlerInterface'];
         $this->debug('Send message: ' . var_export($response, true));
         $connection->send(json_encode($response));
         return;
     }
     $handler->handle($message['event'], $message['data'], $connection, $this->connections);
     return;
 }
Ejemplo 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));
 }
Ejemplo n.º 25
0
 public function onOpen(ConnectionInterface $conn)
 {
     // Store the new connection to send messages to later
     $this->clients[$conn->resourceId] = $conn;
     echo "New connection! ({$conn->resourceId})\n";
     $numRecv = count($this->clients) - 1;
     // When a new client connects, greet him.
     $conn->send(sprintf('Yo connection #%d. You are the %d user(s) connected to this websocket.', $conn->resourceId, $numRecv));
     // And tell the other clients about the new user.
     //        foreach ($this->clients as $client) {
     //            if ($conn !== $client) {
     //                $client->send(sprintf('Connection %d has connected to %d other user(s)', $conn->resourceId, $numRecv));
     //            }
     //        }
 }
 public function onOpen(ConnectionInterface $conn, RequestInterface $request = null)
 {
     // send the 200 OK health response and return
     $response = new Response(200, [], 'Pubsub worker is running!');
     $conn->send((string) $response);
     $conn->close();
 }
Ejemplo 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();
     }
 }
Ejemplo 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);
 }
Ejemplo n.º 29
-2
 public function onMessage(ConnectionInterface $conn, $message, IoServer $server)
 {
     try {
         if ($message == '') {
             $conn->send('');
         }
         if ($message == $this->token) {
             $server->loop->stop();
             $server->socket->shutdown();
             die;
         }
         $ack = call_user_func(array($conn->handler, $this->method), $message);
         $conn->send($ack);
     } catch (\Exception $e) {
         error_log($e->getMessage(), 3, 'server_error.log');
     }
 }
Ejemplo n.º 30
-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;
 }