laravel-websockets/src/LaravelEcho/WebSocket/EchoServer.php

60 lines
1.9 KiB
PHP
Raw Normal View History

2018-11-21 11:13:40 +00:00
<?php
namespace BeyondCode\LaravelWebSockets\LaravelEcho\WebSocket;
use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use BeyondCode\LaravelWebSockets\WebSocketController;
use BeyondCode\LaravelWebSockets\LaravelEcho\Pusher\Channels\ChannelManager;
class EchoServer extends WebSocketController
{
2018-11-21 23:21:42 +00:00
/** @var \BeyondCode\LaravelWebSockets\LaravelEcho\Pusher\Channels\ChannelManager */
2018-11-21 11:13:40 +00:00
protected $channelManager;
public function __construct(ChannelManager $channelManager)
{
$this->channelManager = $channelManager;
}
2018-11-21 23:21:42 +00:00
function onOpen(ConnectionInterface $connection)
2018-11-21 11:13:40 +00:00
{
2018-11-21 14:42:04 +00:00
/**
* There are a couple things we need to do here:
* 1. Authenticate the incoming request by validating the provided APP-ID is known to us (JSON file lookup?)
*/
2018-11-21 11:13:40 +00:00
$socketId = sprintf("%d.%d", getmypid(), random_int(1, 100000000));
// Store the socketId along with the connection so we can retrieve it.
2018-11-21 23:21:42 +00:00
$connection->socketId = $socketId;
2018-11-21 11:13:40 +00:00
2018-11-21 21:11:44 +00:00
/** @var \GuzzleHttp\Psr7\Request $request */
2018-11-21 23:21:42 +00:00
$request = $connection->httpRequest;
2018-11-21 21:11:44 +00:00
$queryParameters = [];
parse_str($request->getUri()->getQuery(), $queryParameters);
2018-11-21 23:21:42 +00:00
$connection->appId = $queryParameters['appId'];
2018-11-21 21:11:44 +00:00
2018-11-21 23:21:42 +00:00
$connection->send(json_encode([
'event' => 'pusher:connection_established',
'data' => json_encode([
'socket_id' => $socketId,
'activity_timeout' => 60,
])
2018-11-21 11:13:40 +00:00
]));
}
2018-11-22 07:31:12 +00:00
public function onMessage(ConnectionInterface $connconnection, MessageInterface $message)
2018-11-21 11:13:40 +00:00
{
2018-11-22 07:31:12 +00:00
$message = RespondableMessageFactory::createForMessage($message, $connconnection, $this->channelManager);
2018-11-21 11:13:40 +00:00
2018-11-21 22:47:46 +00:00
$message->respond();
2018-11-21 11:13:40 +00:00
}
2018-11-21 21:36:50 +00:00
public function onClose(ConnectionInterface $connection)
{
$this->channelManager->removeFromAllChannels($connection);
}
2018-11-21 11:13:40 +00:00
}