PHPMQTT v1.3.0 版本發佈,MQTT 協議解析 & 協程客戶端

v1.3.0 版本新增了一個 Message 類簇,主要方便用於在 Server 中回覆對端 ACK。php

use Simps\MQTT\Protocol\Types;
use Simps\MQTT\Protocol\V3;
use Simps\MQTT\Message\ConnAck;
use Simps\MQTT\Message\PingResp;

$server = new Swoole\Server('127.0.0.1', 1883, SWOOLE_BASE);

$server->set(
    [
        'open_mqtt_protocol' => true,
        'package_max_length' => 2 * 1024 * 1024,
    ]
);

$server->on('connect', function ($server, $fd) {
    echo "Client #{$fd}: Connect.\n";
});

$server->on('receive', function (Swoole\Server $server, $fd, $from_id, $data) {
    $data = V3::unpack($data);
    if (is_array($data) && isset($data['type'])) {
        switch ($data['type']) {
            case Types::CONNECT:
                if ($data['protocol_name'] != 'MQTT') {
                    $server->close($fd);

                    return false;
                }
                $server->send(
                    $fd,
                    (new ConnAck())->setCode(0)
                        ->setSessionPresent(0)
                );
                break;
            case Types::PINGREQ:
                $server->send($fd, (new PingResp()));
                break;
        }
    } else {
        $server->close($fd);
    }
});

$server->on('close', function ($server, $fd) {
    echo "Client #{$fd}: Close.\n";
});

$server->start();

在收到CONNECT包以後,須要回覆CONNACK報文,以前的版本須要用戶手動調用pack類來生成send_datagit

而如今只須要實例化對應的 Message 類,設置所須要的值便可,如 ConnAck :github

  • MQTT3
use Simps\MQTT\Message\ConnAck;

$ack = new ConnAck();
$ack->setCode(0)->setSessionPresent(0);

$server->send($fd, $ack->getContents());
$server->send($fd, $ack);
  • MQTT5
use Simps\MQTT\Message\ConnAck;
use Simps\MQTT\Protocol\ProtocolInterface;

$ack = new ConnAck();
$ack->setProtocolLevel(ProtocolInterface::MQTT_PROTOCOL_LEVEL_5_0)
    ->setCode(0)
    ->setSessionPresent(0)
    ->setProperties([]);

$server->send($fd, $ack->getContents());
$server->send($fd, $ack);

其餘的能夠查看 具體的類 或者 example 文件優化

更新日誌

向下不兼容

  • SUBACK 的payload應該是返回碼,修改鍵名payloadcodes (9e72ce2) (283ff41)

加強

  • 優化 Client recv (#38) (99a85bf)
  • 添加 CONNACK & PUBLISH & PINGRESP Message (700a6c9)
  • 添加 SubAck Message 和更新 getMessageId (09f6334)
  • 添加 DISCONNECT、PUBACK、PUBREC、PUBREL、UNSUBACK (20a78c7)
  • 修改 AbstractConfig (dff6283)
  • 添加 Message 使用示例 (58d5b4a)
  • 添加 getContents 方便在__toString中調用 (a7ba577)
  • 添加 Message 使用文檔 (bab2297)

關於 PHPMQTT

  • MQTT 協議解析 & 協程客戶端
  • 適用於 PHP 的 MQTT 協議解析和協程客戶端
  • 支持 MQTT 協議 3.一、3.1.1 和 5.0 版本,支持 QoS 0、QoS 一、QoS 2
  • 首個支持 MQTT v5.0 協議的 PHP library

文檔:https://mqtt.simps.io
GitHub:https://github.com/simps/mqtt
Gitee:https://gitee.com/phpiot/mqttspa

支持記得點個 Star~日誌

沈唁志公衆號

相關文章
相關標籤/搜索