要使用PHP和WebSocket获取实时数据,您需要先创建一个WebSocket服务器来接收和发送实时数据。
以下是一个简单的示例代码,您可以使用PHP和Ratchet库来创建WebSocket服务器:
- 首先,安装Ratchet库:
composer require cboden/ratchet
- 创建一个WebSocket服务器的PHP文件(server.php):
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);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
$server = new \Ratchet\Server\IoServer(
new \Ratchet\Http\HttpServer(
new \Ratchet\WebSocket\WsServer(
new MyWebSocketServer()
)
),
8080
);
echo "WebSocket server started\n";
$server->run();
- 运行WebSocket服务器:
php server.php
- 创建一个简单的HTML文件来连接WebSocket服务器并接收实时数据(index.html):
Real-time Data
将index.html文件放在您的Web服务器上,并打开它以连接到WebSocket服务器并接收实时数据。您可以在WebSocket服务器的onMessage方法中发送实时数据并在客户端接收和显示。