1. github地址:https://github.com/bluerhinos/phpMQTT
2.安装:composer require bluerhinos/phpmqtt=@dev
3.上代码
<?php
namespace Helper;
use Bluerhinos\phpMQTT;
class Helper
{
/**
* mqtt发布消息
*/
public static function publish($msg)
{
if (is_array($msg)) {
$msg = json_encode($msg);
}
$server = "127.0.0.1"; // change if necessary
$port = 1883; // change if necessary
$username = ""; // set your username
$password = ""; // set your password
$client_id = 'pub_' . uniqid(); // make sure this is unique for connecting to sever - you could use uniqid()
$mqtt = new phpMQTT($server, $port, $client_id);
if ($mqtt->connect(true, NULL, $username, $password)) {
$mqtt->publish("topic", $msg, 0);
$mqtt->close();
return true;
} else {
return false;
}
}
}
4.使用mqtt.fx工具测试,订阅该主题。