我有一个使用Ratchet / PHP的Websocket服务器:
<?php
require __DIR__.'/../vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Mediator;
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Mediator()
)
),
9000
);
$server->run();
?>
Run Code Online (Sandbox Code Playgroud)
调解器类:
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Mediator implements MessageComponentInterface {
protected $clients = [];
public function onOpen(ConnectionInterface $conn) {
$this->clients[$conn->resourceId] = $conn;
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
echo "Incoming: $msg\n";
}
public function onClose(ConnectionInterface $conn) {
unset($this->clients[$conn->resourceId]);
echo "Connection {$conn->resourceId} has disconnected\n"; …Run Code Online (Sandbox Code Playgroud)