【问题标题】:Not able to connect to Mosquitto server using Mosquitto-PHP无法使用 Mosquitto-PHP 连接到 Mosquitto 服务器
【发布时间】:2019-04-04 10:00:04
【问题描述】:

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

【问题讨论】:

  • 你检查过你的 Centos 机器上的防火墙吗?
  • 只显示错误而没有导致它的代码使调试变得非常困难。
  • @hardillb 我已经用代码编辑了这个问题。
  • @MarkSetchell 不。我还没检查过。
  • 它已修复。所需端口被阻止,现在启用 1883/tcp 端口并且现在工作正常。

标签: php mqtt mosquitto phpmqtt


【解决方案1】:

将对$client-&gt;subscribe('#', 1); 的调用移至 onConnect 回调内部。

【讨论】:

    猜你喜欢
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多