在使用 simps/mqtt
连接 MQTT 服务器时,如果遇到 async-io must be used in PHP CLI mode
错误,通常是因为 simps/mqtt
依赖的异步 I/O 库(如 workerman
或 swoole
)需要在 CLI 模式下运行,而你在 Web 环境下(如通过 Apache 或 Nginx)运行了代码。
在 CLI 模式下运行代码:
例如,创建一个 mqtt_client.php
文件,内容如下:
<?php
require __DIR__ . '/vendor/autoload.php';
use Simps\MQTT\Client;
use Simps\MQTT\Config\ClientConfig;
$config = new ClientConfig();
$config->setClientId('your_client_id');
$config->setKeepAlive(60);
$client = new Client('mqtt://your_mqtt_broker:1883', $config);
$client->onConnect(function ($client) {
echo "Connected\n";
$client->subscribe('your_topic');
});
$client->onMessage(function ($topic, $message) {
echo "Received message on topic {$topic}: {$message}\n";
});
$client->connect();
$client->loop();
bash
php mqtt_client.php
使用 WebSocket 或其他协议:
simps/mqtt
的 WebSocket 客户端来连接 MQTT 服务器。使用 Swoole 或 Workerman 的 HTTP 服务器:
例如,使用 Swoole 创建一个 HTTP 服务器:
<?php
require __DIR__ . '/vendor/autoload.php';
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
$server = new Server("0.0.0.0", 9501);
$server->on("start", function (Server $server) {
echo "Swoole HTTP server is started at http://0.0.0.0:9501\n";
});
$server->on("request", function (Request $request, Response $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello World\n");
});
$server->start();
async-io must be used in PHP CLI mode
错误是由于异步 I/O 库需要在 CLI 模式下运行。解决方法包括在 CLI 模式下运行代码、使用 WebSocket 协议、或者使用 Swoole/Workerman 提供的 HTTP 服务器来替代传统的 Web 服务器。根据你的具体需求选择合适的解决方案。