58 lines
1.5 KiB
PHP
58 lines
1.5 KiB
PHP
<?php
|
|
require __DIR__ . '/vendor/autoload.php';
|
|
|
|
use Ratchet\MessageComponentInterface;
|
|
use Ratchet\ConnectionInterface;
|
|
|
|
class SimpleChat implements MessageComponentInterface {
|
|
|
|
protected $clients = [];
|
|
|
|
public function onOpen(ConnectionInterface $conn) {
|
|
$this->clients[$conn->resourceId] = $conn;
|
|
echo "Client {$conn->resourceId} connected\n";
|
|
}
|
|
|
|
public function onMessage(ConnectionInterface $from, $msg) {
|
|
$data = json_decode($msg, true);
|
|
|
|
if (!$data) {
|
|
return;
|
|
}
|
|
|
|
if ($data['type'] === "send_message") {
|
|
$out = json_encode([
|
|
"type" => "chat_message",
|
|
"from" => $from->resourceId,
|
|
"text" => $data['text']
|
|
]);
|
|
|
|
foreach ($this->clients as $client) {
|
|
$client->send($out);
|
|
}
|
|
}
|
|
}
|
|
|
|
public function onClose(ConnectionInterface $conn) {
|
|
unset($this->clients[$conn->resourceId]);
|
|
echo "Client {$conn->resourceId} disconnected\n";
|
|
}
|
|
|
|
public function onError(ConnectionInterface $conn, \Exception $e) {
|
|
echo "Error: {$e->getMessage()}\n";
|
|
$conn->close();
|
|
}
|
|
}
|
|
|
|
$server = Ratchet\Server\IoServer::factory(
|
|
new Ratchet\Http\HttpServer(
|
|
new Ratchet\WebSocket\WsServer(
|
|
new SimpleChat()
|
|
)
|
|
),
|
|
8080
|
|
);
|
|
|
|
echo "Simple Chat WebSocket running on port 8080\n";
|
|
$server->run();
|