四时宝库

程序员的知识宝库

MQTT基础-连接demo与连接报文分析

大家好,我是yangyang.接着给大家带来mqtt基础知识第三篇:使用php连接mqtt

php-mqtt/client

php-mqtt/client 是 composer 上下载量最高的 MQTT 客户端库,它允许您连接到 MQTT 代理,您可以在其中发布消息和订阅主题。目前支持mqtt3、3.1、3.1.1,暂不支持mqtt5.

建立连接、订阅主题、发布主题、循环监听

<?php

require('vendor/autoload.php');

use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;

$server   = '127.0.0.1';
$port     = 1883;
$clientId = rand(5, 15);
$username = 'emqx_user';
$password = 'public';
$clean_session = false;
$mqtt_version = MqttClient::MQTT_3_1_1;

$connectionSettings  = (new ConnectionSettings)
  ->setUsername($username)
  ->setPassword($password)
  ->setKeepAliveInterval(60)
  // Last Will 设置
  ->setLastWillTopic('emqx/test/last-will')
  ->setLastWillMessage('client disconnect')
  ->setLastWillQualityOfService(1);


$mqtt = new MqttClient($server, $port, $clientId, $mqtt_version);

$mqtt->connect($connectionSettings, $clean_session);
printf("client connected\n");

$mqtt->subscribe('emqx/test', function ($topic, $message) {
    printf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);

for ($i = 0; $i< 10; $i++) {
  $payload = array(
    'protocol' => 'tcp',
    'date' => date('Y-m-d H:i:s'),
    'url' => 'https://github.com/emqx/MQTT-Client-Examples'
  );
  $mqtt->publish(
    // topic
    'emqx/test',
    // payload
    json_encode($payload),
    // qos
    0,
    // retain
    true
  );
  printf("msg $i send\n");
  sleep(1);
}

$mqtt->loop(true);

更多使用请参考:https://github.com/php-mqtt/client

bluerhinos/phpMQTT

star最高,引入少.方便学习源码参考协议解析

建立连接成功后,发布主题并断开.

require('../phpMQTT.php');

$server = '127.0.0.1';     // change if necessary 127.0.0.1
$port = 1883;                     // change if necessary
$username = 'wanzij.cn';                   // set your username wanzij.cn
$password = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJieXQiLCJpYXQiOjE3MDg5MjQyMjcsImV4cCI6MTcwODkyNzgyN30.lMDByZf3rHTB9xGhq_ZbkSzUzddcMFpy59YE-XGjT5o';                   // set your password eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJieXQiLCJpYXQiOjE3MDg5MjIyNTQsImV4cCI6MTcwODkyNTg1NH0.ajrb5CLsFLF5MpCsk8kf8GnJepdLBpuClhR2kUZuUJ4
$client_id = 'test1'; // make sure this is unique for connecting to sever - you could use uniqid()

$mqtt = new Bluerhinos\phpMQTT($server, $port, $client_id);
if ($mqtt->connect(true, NULL, $username, $password)) {
	$mqtt->publish('bluerhinos/phpMQTT/examples/publishtest', 'Hello World! at ' . date('r'), 0, false);
	$mqtt->close();
} else {
    echo "Time out!\n";
}

不过,这个包文件解析处理有一点点bug.就是在连接的时候,如果可变头部(Variable Header)内容过大,它计算head长度就不对了,比如密码很长,就会导致连接不上,认证失败.我简单给大家看下有问题的源码:


因为作者对于head是计算了固定头部和可变头部的,这样当可变头部里的某一项很大时,长度就不只是2个字节长度了,所以不能是取2个字节,而是需要把header buffer 拼接到一起:fwrite($this->socket, $head.$buffer);

workerman/mqtt

workerman\mqtt 是一个基于workerman的异步mqtt 客户端库,可用于接收或者发送mqtt协议的消息。支持QoS 0QoS 1QoS 2。支持MQTT 3.1 3.1.1 5版本。链接:workemran/mqtt-workerman手册


<?php
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker();
$worker->onWorkerStart = function(){
    $mqtt = new Workerman\Mqtt\Client('mqtt://test.mosquitto.org:1883');
    $mqtt->onConnect = function($mqtt) {
        $mqtt->subscribe('test');
    };
    $mqtt->onMessage = function($topic, $content){
        var_dump($topic, $content);
    };
    $mqtt->connect();
};
Worker::runAll();

simps/mqtt

simps/mqtt是一个swoole实现的协程客户端,支持 MQTT 协议 3.1、3.1.1 和 5.0 版本。链接:mqtt/examples at master · simps/mqtt · GitHub

# 官方有支持fpm的demo
<?php
/**
 * This file is part of Simps.
 *
 * @link     https://github.com/simps/mqtt
 * @contact  Lu Fei <lufei@simps.io>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

include_once __DIR__ . '/bootstrap.php';

use Simps\MQTT\Client;
use Swoole\Coroutine;

Coroutine\run(function () {
    $client = new Client(SIMPS_MQTT_LOCAL_HOST, SIMPS_MQTT_PORT, getTestConnectConfig());
    $client->connect();
    while (true) {
        $response = $client->publish('simps-mqtt/user001/update', '{"time":' . time() . '}', 1);
        var_dump($response);
        Coroutine::sleep(3);
    }
});

总结:如果是传递项目中短连接(就是接口请求发送一次,然后连接发布主题信息后就关闭),可以用前面两个.如果需要一直监听,推荐workerman/mqtt

前端:浏览器和nodejs服务端

它们都可以使用mqtt.js作为客户端连接.区别在于:浏览器端只能通过ws 和wss 连接;具体建议大家阅读文档中有关连接部分内容,链接:https://github.com/mqttjs/MQTT.js

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接