PHP标准MQTT服务器推送
<pre><code class="language-php">&lt;?php
use Mosquitto\Client;
## 接入点地址,购买实例后从控制台获取
$endPoint = '39.98.75.131';
$port = 1883;
$username = 'mqttpay';
$password = 'mqttpay';
## MQTT 客户端ID 后缀,DeviceId,业务方自由指定,需要保证全局唯一,禁止 2 个客户端连接使用同一个 ID
## 设备IMEI号码
$deviceId = '352736082691067';
$qos = 2;
$keepalive = 90;
$cleanSession = true;
$clientId = $deviceId;
## 发送端ClientID,请修改或添加特定字符串,保证全局唯一
$masterClientId='ZKC20191010master';
echo $clientId . &quot;\n&quot;;
$mid = 0;
$mqttClient = new Mosquitto\Client($masterClientId, $cleanSession);
echo &quot;UserName:&quot; . $username . &quot; Password:&quot; . $password . &quot;\n&quot;;
$mqttClient-&amp;setCredentials($username, $password);
## 设置连接成功回调
$mqttClient-&amp;onConnect(function ($rc, $message) use ($mqttClient, &amp;amp;$mid, $topic, $qos, $clientId) {
echo date('Y-m-d H:i:s').&quot; 连接成功:Connnect to Server Code is &quot; . $rc . &quot; message is &quot; . $message . &quot;\n&quot;;
$mqttP2PTopic = $clientId;
$ZPL = $deviceId.&quot;|1007|2019022611153312312345|566.88|2001&quot;;
echo date('Y-m-d H:i:s').&quot; 推送Topic:&quot;.$mqttP2PTopic.&quot;\n&quot;;
echo date('Y-m-d H:i:s').&quot; 推送内容:&quot;.$ZPL.&quot;\n&quot;;
$mqttClient-&amp;publish($mqttP2PTopic, $ZPL, $qos);
## 打印机需要发送十六进制数组,需要对hex数据pack操作
## 例如打印内容为:$ZPL = &quot;1E1003000a414243440d0a1B636f90&quot;;
## 则需要$mqttClient-&amp;publish($mqttP2PTopic, pack(&quot;H*&quot;,$ZPL), $qos);
});
## 设置发送成功回调
$mqttClient-&amp;onPublish(function ($publishedId) use ($mqttClient, $mid) {
echo date('Y-m-d H:i:s').&quot; 发送成功:publish message success &quot; . $mid . &quot;\n&quot;;
});
## 设置消息接收回调
$mqttClient-&amp;onMessage(function ($message) {
echo date('Y-m-d H:i:s').&quot; 接收回调:Message From mqtt, topic is &quot; . $message-&amp;topic . &quot; qos is &quot; . $message-&amp;qos . &quot; messageId is &quot; . $message-&amp;mid . &quot; payload is &quot; . $message-&amp;payload . &quot;\n&quot;;
});
$mqttClient-&amp;connect($endPoint, $port, $keepalive);
$mqttClient-&amp;loopForever();
echo &quot;Finished&quot;;</code></pre>