一个基于 swoole 的异步 mqtt 客户端库,可用于接收或者发送 mqtt 协议的消息

一个基于 swoole 的异步 mqtt 客户端库,可用于接收或者发送 mqtt 协议的消息。支持 QoS 0、QoS 1、QoS 2。支持 MQTT 3.1 和 3.1.1 版本.

安装

composer require try-to/swoole_mqtt

Example

subscribe.php

<?php

use TrytoMqtt\Client;

require_once __DIR__ . '/vendor/autoload.php';

$options = [
    'clean_session' => false,
    'client_id' => 'demo-subscribe-123456',
    'username' => '',
    'password' => '',
];

$mqtt = new Client('127.0.0.1', 1883, $options);

$mqtt->onConnect = function ($mqtt) {
    $mqtt->subscribe('/World');
};

$mqtt->onMessage = function ($topic, $content) {
    var_dump($topic, $content);
};

$mqtt->onError = function ($exception) use ($mqtt) {
    echo "error\n";
    // $mqtt->reconnect(1000);
};

$mqtt->onClose = function () {
    echo "close\n";
};

$mqtt->connect();

命令行运行 php subscribe.php 启动

publish.php

<?php

use TrytoMqtt\Client;

require_once __DIR__ . '/../vendor/autoload.php';

$options = [
    'clean_session' => false,
    'client_id' => 'demo-publish-123456',
    'username' => '',
    'password' => '',
];

$mqtt = new Client('127.0.0.1', 1883, $options);

$mqtt->onConnect = function ($mqtt) {
    $mqtt->publish('/World', 'hello swoole mqtt');
};

$mqtt->onError = function ($exception) {
    echo "error\n";
};

$mqtt->onClose = function () {
    echo "close\n";
};

$mqtt->connect();

命令行运行 php publish.php 启动

实现的接口

  • Client::__construct()
  • Client::connect()
  • Client::reconnect()
  • Client::publish()
  • Client::subscribe()
  • Client::unsubscribe()
  • Client::disconnect()
  • Client::close()
  • callback onConnect
  • callback onMessage
  • callback onError
  • callback onClose

地址

github地址
码云地址

    原文作者:后端开发
    原文地址: https://segmentfault.com/a/1190000017453834
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞