Skip to content

Instantly share code, notes, and snippets.

@w33zy
Forked from tsh-code/RatchetServer.php
Created November 15, 2019 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w33zy/44e1bf94635fd5af8a933b5ab2799b41 to your computer and use it in GitHub Desktop.
Save w33zy/44e1bf94635fd5af8a933b5ab2799b41 to your computer and use it in GitHub Desktop.
<?php
namespace App\Services;
use Ratchet\Http\HttpServer;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
class RatchetServer implements MessageComponentInterface
{
protected $clients;
public function start($port)
{
$server = IoServer::factory(
new HttpServer(
new WsServer(
$this
)
),
$port
);
$server->run();
}
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment