本文整理汇总了PHP中Ratchet\ConnectionInterface类的典型用法代码示例。如果您正苦于以下问题:PHP ConnectionInterface类的具体用法?PHP ConnectionInterface怎么用?PHP ConnectionInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ConnectionInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: onOpen
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();
}
示例2: onCall
/**
* 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]));
}
示例3: dispatch
/**
* @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;
}
示例4: onCall
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
}
示例5: onOpen
/**
* @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();
}
示例6: onMessage
/**
* 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);
}
}
示例7: onOpen
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();
}
示例8: onMessage
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";
}
示例9: onError
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 */
}
}
示例10: onMessage
function onMessage(ConnectionInterface $from, $msg)
{
$msg = explode(' ', $msg);
$msg[0] = 'pong';
$from->send(implode(' ', $msg));
$from->close();
}
示例11: onCall
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));
}
示例12: onOpen
/**
* {@inheritdoc}
*/
function onOpen(ConnectionInterface $conn)
{
if ($this->isBlocked($conn->remoteAddress)) {
return $conn->close();
}
return $this->_decorating->onOpen($conn);
}
示例13: onError
/**
* 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();
}
示例14: onOpen
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);
}
示例15: onMessage
/**
* 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);
}