共计 1670 个字符,预计需要花费 5 分钟才能阅读完成。
要使用 PHP 和 WebSocket 获取实时数据,您需要先创建一个 WebSocket 服务器来接收和发送实时数据。
以下是一个简单的示例代码,您可以使用 PHP 和 Ratchet 库来创建 WebSocket 服务器:
- 首先,安装 Ratchet 库:
composer require cboden/ratchet
- 创建一个 WebSocket 服务器的 PHP 文件(server.php):
<?php
require 'vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
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) {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):
<!DOCTYPE html>
<html>
<head>
<title>Real-time Data</title>
</head>
<body>
<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.innerHTML = e.data;
messages.appendChild(message);
};
</script>
</body>
</html>
将 index.html 文件放在您的 Web 服务器上,并打开它以连接到 WebSocket 服务器并接收实时数据。您可以在 WebSocket 服务器的 onMessage 方法中发送实时数据并在客户端接收和显示。
丸趣 TV 网 – 提供最优质的资源集合!
正文完