Skip to content

Instantly share code, notes, and snippets.

@tsh-code
Created March 7, 2019 09:58
Show Gist options
  • Save tsh-code/dfefcb76aed58e6b3b8f1e0cd59f7cc4 to your computer and use it in GitHub Desktop.
Save tsh-code/dfefcb76aed58e6b3b8f1e0cd59f7cc4 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