2023-01-30 22:19:04 +01:00
|
|
|
<?php
|
2023-01-31 00:57:06 +01:00
|
|
|
|
2023-01-30 22:19:04 +01:00
|
|
|
use Ratchet\MessageComponentInterface;
|
|
|
|
use Ratchet\ConnectionInterface;
|
|
|
|
|
2023-01-31 00:57:06 +01:00
|
|
|
// Make sure composer dependencies have been installed
|
|
|
|
require __DIR__ . '/vendor/autoload.php';
|
2023-01-30 22:19:04 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* chat.php
|
|
|
|
* Send any incoming messages to all connected clients (except sender)
|
|
|
|
*/
|
2023-01-31 00:57:06 +01:00
|
|
|
class MyChat implements MessageComponentInterface
|
|
|
|
{
|
2023-01-30 22:19:04 +01:00
|
|
|
protected $clients;
|
|
|
|
|
2023-01-31 00:57:06 +01:00
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
$this->clients = new \SplObjectStorage();
|
2023-01-30 22:19:04 +01:00
|
|
|
}
|
|
|
|
|
2023-01-31 00:57:06 +01:00
|
|
|
public function onOpen(ConnectionInterface $conn)
|
|
|
|
{
|
2023-01-30 22:19:04 +01:00
|
|
|
$this->clients->attach($conn);
|
|
|
|
}
|
|
|
|
|
2023-01-31 00:57:06 +01:00
|
|
|
public function onMessage(ConnectionInterface $from, $msg)
|
|
|
|
{
|
2023-01-30 22:19:04 +01:00
|
|
|
foreach ($this->clients as $client) {
|
|
|
|
if ($from != $client) {
|
|
|
|
$client->send($msg);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-31 00:57:06 +01:00
|
|
|
public function onClose(ConnectionInterface $conn)
|
|
|
|
{
|
2023-01-30 22:19:04 +01:00
|
|
|
$this->clients->detach($conn);
|
|
|
|
}
|
|
|
|
|
2023-01-31 00:57:06 +01:00
|
|
|
public function onError(ConnectionInterface $conn, \Exception $e)
|
|
|
|
{
|
2023-01-30 22:19:04 +01:00
|
|
|
$conn->close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-31 00:57:06 +01:00
|
|
|
// Run the server application through the WebSocket protocol on port 8080
|
|
|
|
$app = new Ratchet\App('localhost', 8080);
|
|
|
|
$app->route('/chat', new MyChat(), array('*'));
|
|
|
|
$app->route('/echo', new Ratchet\Server\EchoServer(), array('*'));
|
|
|
|
$app->run();
|