上个版本发布的知乎文章中有用户评论,遇到了握手失败的情况,联系了我之后进行了测试,我这里确实没问题,不过我删除了一段代码:
$will = [
'topic' => '',
'qos' => 0,
'retain' => 0,
'message' => '',
];
$client->connect(true, $will);
改为了直接进行connect
$client->connect();
由于使用的是 MQTT3,所以没有 MQTT5 中的 code 属性,需要通过抓包才可以获取到错误原因。
这里换为 MQTT5 之后就可以直接获取到错误原因,如以下代码就可以获取到错误原因
use Simps\MQTT\Client;
use Simps\MQTT\Config\ClientConfig;
use Simps\MQTT\Hex\ReasonCode;
use function Swoole\Coroutine\run;
run(function () {
$config = new ClientConfig();
$config->setUserName('')
->setPassword('')
->setClientId(Client::genClientID())
->setKeepAlive(10)
->setProtocolLevel(5)
->setDelay(3000) // 3s
->setMaxAttempts(5)
->setSwooleConfig([
'open_mqtt_protocol' => true,
'package_max_length' => 2 * 1024 * 1024,
]);
$client = new Client('broker.emqx.io', 1883, $config);
$will = [
'topic' => '',
'qos' => 0,
'retain' => 0,
'message' => 'byebye',
];
$res = $client->connect(true, $will);
var_dump($res, ReasonCode::getReasonPhrase($res['code']));
});
将 code 换为原因,就可以获取到错误原因为:Topic Name invalid
array(3) {
["type"]=>
int(2)
["session_present"]=>
int(0)
["code"]=>
int(144)
}
string(18) "Topic Name invalid"
查看 MQTT 协议文档,会发现:
The Will Topic MUST be a UTF-8 Encoded String as defined
遗嘱消息中的 topic 不能为空,必须是一个有效的 UTF-8 字符串,长度大于 0
所以这里此版本中增加了限制,如果存在遗嘱消息,并且 topic 为空,则会直接抛出异常:
PHP Fatal error: Uncaught Simps\MQTT\Exception\ProtocolException: Topic cannot be empty
文档:https://mqtt.simps.io GitHub:https://github.com/simps/mqtt Gitee:https://gitee.com/phpiot/mqtt
支持记得点个 Star~
好文和朋友一起看~