WebSockets на PHP с Ratchet
WebSockets позволяют создавать двусторонние соединения между сервером и браузером без постоянных HTTP-запросов. Ratchet — популярная PHP-библиотека поверх ReactPHP для построения WebSocket-серверов.
Установка Ratchet
composer require cboden/ratchetПростой WebSocket-сервер
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 ($client !== $from) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(new WsServer(new Chat())),
8080
);
$server->run();Клиентский JavaScript
const ws = new WebSocket('wss://yourdomain.com/ws');
ws.onopen = () => console.log('Connected');
ws.onmessage = (e) => console.log('Message:', e.data);
// Отправка сообщения
ws.send(JSON.stringify({ user: 'Alice', text: 'Hello!' }));Nginx Reverse Proxy для WebSockets
server {
listen 443 ssl;
server_name yourdomain.com;
location /ws {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 86400;
}
}Автозапуск через systemd
[Unit]
Description=Ratchet WebSocket Server
After=network.target
[Service]
Type=simple
User=www-data
ExecStart=/usr/bin/php /var/www/html/ws-server.php
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.targetsystemctl enable ratchet-ws
systemctl start ratchet-ws
systemctl status ratchet-wsАльтернатива: Для высоконагруженных систем рассмотрите Swoole или ReactPHP напрямую — они производительнее Ratchet и поддерживают корутины.