在 PHP 中实现排名的实时更新,可以使用以下几种方法:
// server.php
$rank = get_rank(); // 获取排名数据
echo json_encode($rank); // 将排名数据以 JSON 格式返回
// client.html
setInterval(function() {
  fetch('/server.php')
    .then(response => response.json())
    .then(data => {
      console.log('排名更新:', data);
    });
}, 5000); // 每隔 5 秒发送一次请求
// server.php
while (true) {
  $rank = get_rank(); // 获取排名数据
  if ($rank !== false) { // 如果有了新的排名数据
    echo json_encode($rank); // 将排名数据以 JSON 格式返回
    break;
  }
  sleep(1); // 等待 1 秒
}
// server.php
$ws = new WebSocket\Server("ws://0.0.0.0:8080");
$ws->on('open', function ($ws, $request) {
  // 当客户端连接成功时,发送初始排名数据
  $rank = get_rank();
  $ws->send(json_encode($rank));
});
$ws->on('message', function ($ws, $message) {
  // 当收到客户端发来的消息时,处理请求(此处未使用)
});
$ws->on('close', function ($ws, $code, $reason) {
  // 当客户端断开连接时,关闭 WebSocket 服务
});
// client.html
const ws = new WebSocket('ws://your_server_address:8080');
ws.addEventListener('open', function (event) {
  console.log('WebSocket 连接已打开');
});
ws.addEventListener('message', function (event) {
  const rank = JSON.parse(event.data);
  console.log('排名更新:', rank);
});
ws.addEventListener('close', function (event) {
  console.log('WebSocket 连接已关闭');
});
安装 Ratchet:
composer require cboden/ratchet
创建 WebSocket 服务器:
// myWebSocketServer.php
require 'vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ),
    8080
);
$server->run();
创建处理排名逻辑的类:
// MyApp/Chat.php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
    protected $clients;
    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }
    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }
    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from !== $client) {
                $client->send($msg);
            }
        }
    }
    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
    }
    public function onError(ConnectionInterface $conn, \Exception $e) {
        $conn->close();
    }
    public function getRank() {
        // 获取排名数据的逻辑
    }
}
客户端代码与长轮询示例相同。
以上就是在 PHP 中实现排名实时更新的几种方法。你可以根据实际需求和技术栈选择合适的方法。