在使用ThinkPHP6框架下通过simps/mqtt
连接阿里云物联网平台MQTT时,遇到“SwooleCoroutineClient::connect(): async-io must be used in PHP CLI mode”错误,通常是因为Swoole的协程客户端(Swoole\Coroutine\Client
)只能在PHP CLI模式下使用,而不能在FPM或Apache等Web服务器模式下使用。
切换到CLI模式运行:
步骤:
app/command
目录下创建一个新的命令文件,例如MqttCommand.php
。示例代码:
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use Simps\MQTT\Client;
class MqttCommand extends Command
{
protected function configure()
{
$this->setName('mqtt:connect')->setDescription('Connect to MQTT');
}
protected function execute(Input $input, Output $output)
{
$config = [
'host' => 'your-mqtt-endpoint',
'port' => 1883,
'username' => 'your-username',
'password' => 'your-password',
'client_id' => 'your-client-id',
];
$client = new Client($config);
$client->connect();
// 订阅主题
$client->subscribe('your/topic');
// 处理消息
$client->loop(function ($message) use ($output) {
$output->writeln("Received message: " . $message['content']);
});
}
}
运行命令:
php think mqtt:connect
使用Swoole的HTTP服务器:
步骤:
示例代码:
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
$http = new Server("0.0.0.0", 9501);
$http->on("start", function ($server) {
echo "Swoole HTTP server is started at http://127.0.0.1:9501\n";
});
$http->on("request", function (Request $request, Response $response) {
// 在这里处理ThinkPHP6的请求
$response->header("Content-Type", "text/plain");
$response->end("Hello World\n");
});
$http->start();
避免在Web请求中使用Swoole协程:
php-mqtt/client
,它不依赖于Swoole协程。示例代码:
use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\ConnectionSettings;
$server = 'your-mqtt-endpoint';
$port = 1883;
$clientId = 'your-client-id';
$username = 'your-username';
$password = 'your-password';
$mqtt = new MqttClient($server, $port, $clientId);
$connectionSettings = (new ConnectionSettings)
->setUsername($username)
->setPassword($password);
$mqtt->connect($connectionSettings, true);
$mqtt->subscribe('your/topic', function ($topic, $message) {
echo "Received message on topic [$topic]: $message\n";
});
$mqtt->loop(true);
根据你的具体需求和环境选择合适的解决方案。