Created
March 7, 2019 09:58
-
-
Save tsh-code/dfefcb76aed58e6b3b8f1e0cd59f7cc4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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