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

时间:2019-04-04 10:00:04

标签: php mqtt mosquitto phpmqtt

我已在centos服务器上安装了mosquitto代理。为了通讯,我安装了Mosquitto-PHP库。发布者和订阅者在同一台服务器上工作正常,但是当我尝试从此centos服务器发布消息并从本地计算机(ubuntu)运行订阅者脚本时,出现以下错误-

PHP Fatal error: Uncaught Mosquitto\Exception: The client is not currently connected. in /home/sujit/Desktop/php_test.php:12
Stack trace:
#0 /home/sujit/Desktop/php_test.php(12): Mosquitto\Client->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 Mosquitto\Client(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}\n";
}

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

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

function disconnect() {
        echo "Disconnected cleanly\n";
}

1 个答案:

答案 0 :(得分:0)

将对$client->subscribe('#', 1);的调用移到onConnect回调中。