Sujit Verma
Sujit Verma

Reputation: 180

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

Upvotes: 0

Views: 915

Answers (1)

hardillb
hardillb

Reputation: 59751

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

Upvotes: 0

Related Questions