use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
class MyWebSocket implements MessageComponentInterface {
public function onOpen(ConnectionInterface $conn) {
echo New connection established: {$conn-remoteAddress}\n;
}
public function onMessage(ConnectionInterface $conn, $msg) {
echo Received message: {$msg}\n;
$conn-send(Echo: {$msg});
}
public function onClose(ConnectionInterface $conn) {
echo Connection closed: {$conn-remoteAddress}\n;
}
public function onError(ConnectionInterface $conn, $error) {
echo Error: {$error}\n;
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new MyWebSocket()
)
),
8080
);
$server-run();
启动服务器
bash
php server.php
客户端测试(JavaScript):
html
<!DOCTYPE html
<html
<body
<script
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = function(event) {
console.log('Received:', event.data);
};
ws.send('Hello from client!');
</script
</body
</html