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

42次阅读

共计 1313 个字符,预计需要花费 4 分钟才能阅读完成。

一个基于 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 地址码云地址

正文完
 0