无法使用Mosquitto-PHP连接到Mosquitto服务器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法使用Mosquitto-PHP连接到Mosquitto服务器相关的知识,希望对你有一定的参考价值。

我在centos服务器上安装了mosquitto broker。为了沟通,我安装了Mosquitto-php库。发布者和订阅者在同一台服务器上正常工作,但当我尝试从这个centos服务器发布消息并从本地机器(ubuntu)运行订阅者脚本时,然后收到以下错误 -

PHP Fatal error: Uncaught MosquittoException: The client is not currently connected. in /home/sujit/Desktop/php_test.php:12
Stack trace:
#0 /home/sujit/Desktop/php_test.php(12): MosquittoClient->subscribe('#', 1)
#1 {main}
thrown in /home/sujit/Desktop/php_test.php on line 12

Mosquitto-PHP库已安装在本地计算机上。

下面是我正在运行的subscriber.php文件 -

<?php
define('BROKER', 'ip address of server');
define('PORT', 1883);
define('CLIENT_ID', "pubclient_" . getmypid());

$client = new MosquittoClient(CLIENT_ID);
$client->onConnect('connect');
$client->onDisconnect('disconnect');
$client->onSubscribe('subscribe');
$client->onMessage('message');
$client->connect(BROKER, PORT, 60);
$client->subscribe('#', 1); // Subscribe to all messages

$client->loopForever();

function connect($r) {
        echo "Received response code {$r}
";
}

function subscribe() {
        echo "Subscribed to a topic
";
}

function message($message) {
        printf("Got a message on topic %s with payload:
%s
", $message->topic, $message->payload);
}

function disconnect() {
        echo "Disconnected cleanly
";
}
答案

将调用移动到$client->subscribe('#', 1);到onConnect回调内部。

以上是关于无法使用Mosquitto-PHP连接到Mosquitto服务器的主要内容,如果未能解决你的问题,请参考以下文章

为啥即使使用 Colab Pro 帐户也无法连接到 GPU 后端?

PEAR Mail 无法连接到 Gmail SMTP,无法连接到套接字

无法使用 Python 连接到 MSSQL Server 数据库

无法连接到虚拟机怎么解决?怎么解决?

VMware Workstation 无法连接到虚拟机

无法使用 Windows 域\用户名连接到 ADAM