简体   繁体   中英

Not able to connect to Mosquitto server using Mosquitto-PHP

I have installed mosquitto broker on a centos server. for communication I installed Mosquitto-PHP library. publisher and subscriber are working fine on the same server but when I am trying to publish message from this centos server and running subscriber script from local machine (ubuntu) then getting following error -

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 library already installed on local machine.

Below is the subscriber.php file that I am running -

<?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";
}

Move the call to $client->subscribe('#', 1); to inside the the onConnect callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM