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

74 lines
2.2 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
{
/** @var ChannelManager */
protected $channelManager;
public function __construct(ChannelManager $channelManager)
{
$this->channelManager = $channelManager;
}
/**
* When a new connection is opened it will be passed to this method
2018-11-21 22:47:46 +00:00
*
2018-11-21 11:13:40 +00:00
* @param ConnectionInterface $conn The socket/connection that just connected to your application
2018-11-21 22:47:46 +00:00
*
2018-11-21 11:13:40 +00:00
* @throws \Exception
*/
function onOpen(ConnectionInterface $conn)
{
dump("Client connected");
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.
$conn->socketId = $socketId;
2018-11-21 21:11:44 +00:00
/** @var \GuzzleHttp\Psr7\Request $request */
$request = $conn->httpRequest;
$queryParameters = [];
parse_str($request->getUri()->getQuery(), $queryParameters);
$conn->appId = $queryParameters['appId'];
2018-11-21 11:13:40 +00:00
$conn->send($this->buildPayload('pusher:connection_established', [
'socket_id' => $socketId,
'activity_timeout' => 60,
]));
}
2018-11-21 22:47:46 +00:00
public function onMessage(ConnectionInterface $conn, MessageInterface $message)
2018-11-21 11:13:40 +00:00
{
2018-11-21 22:47:46 +00:00
$message = RespondableMessageFactory::createForMessage($message, $conn, $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
protected function buildPayload($event, $data = [])
{
return json_encode([
'event' => $event,
'data' => json_encode($data)
]);
}
}