要通過WebSocket實(shí)時(shí)更新數(shù)據(jù),首先需要在PHP中創(chuàng)建一個(gè)WebSocket服務(wù)器??梢允褂玫谌綆烊鏡atchet或ReactPHP來實(shí)現(xiàn)WebSocket服務(wù)器。下面以Ratchet為例,介紹如何在PHP中通過WebSocket實(shí)時(shí)更新數(shù)據(jù):
composer require cboden/ratchet
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
require 'vendor/autoload.php';
class MyWebSocketServer implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
// 處理客戶端發(fā)送的消息
foreach ($this->clients as $client) {
$client->send($msg); // 發(fā)送消息給所有客戶端
}
}
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\WebSocket\WsServer(new MyWebSocketServer);
$server = new Ratchet\Http\HttpServer($server);
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server('0.0.0.0:8080', $loop);
$server = new Ratchet\Server\IoServer($server, $socket, $loop);
$server->run();
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Test</title>
</head>
<body>
<input type="text" id="input" placeholder="Enter message">
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
var conn = new WebSocket('ws://localhost:8080');
conn.onmessage = function(e) {
var messages = document.getElementById('messages');
var message = document.createElement('li');
message.appendChild(document.createTextNode(e.data));
messages.appendChild(message);
};
function sendMessage() {
var input = document.getElementById('input');
conn.send(input.value);
input.value = '';
}
</script>
</body>
</html>
通過以上步驟,就可以在PHP中通過WebSocket實(shí)時(shí)更新數(shù)據(jù)了。在服務(wù)器端接收到數(shù)據(jù)時(shí),會將數(shù)據(jù)發(fā)送給所有連接的客戶端,客戶端接收數(shù)據(jù)后可以實(shí)時(shí)更新頁面。