EMP 實現訊息釋出訂閱
阿新 • • 發佈:2018-11-19
官網文件
http://emqtt.com/docs/v2/index.html
php 實現訊息釋出
- 使用第三方包
bluerhinos/phpmqtt
$mqtt = new phpMQTT("localhost", 1883, "clientId");
//Change ClientId to something unique,此處必須唯一,一個客戶端對應一個id
if ($mqtt->connect()) {
for($i = 0; $i < 20; $i++) {
sleep(1);
// $mqtt->publish('/Worldd','Hello new '.$i.'laravel!',0);
$mqtt->publish("World","Hello laravel! at ".date("r"),0);
}
$mqtt->close();
}
訊息訂閱
- php實現
<?php
require dirname(__DIR__) . "/vendor/autoload.php";
use Bluerhinos\phpMQTT;
$server = "localhost"; // change if necessary
$port = 1883; // change if necessary
$username = ""; // set your username
$password = ""; // set your password
$client_id = "phh-subscriber"; // make sure this is unique for connecting to sever - you could use uniqid()
$micro_time = round(microtime(true) * 1000);
$client_id = $client_id . $micro_time;
$mqtt = new phpMQTT($server, $port, $client_id);
if (!$mqtt->connect(true, NULL, $username, $password)) {
exit(1);
}
function procmsg($topic, $msg)
{
echo "Msg Recieved: " . date("r") . "\n";
echo "Topic: {$topic}\n\n";
echo "\t$msg\n\n";
}
$topics['World'] = array("qos" => 0, "function" => "procmsg");
$mqtt->subscribe($topics, 0);
while ($mqtt->proc()) {
}
$mqtt->close();
- js websocket 訂閱訊息
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
<script type="text/javascript">
client = new Paho.MQTT.Client("localhost", Number(8083), "mqttjs_f3244323b7");//建立客戶端例項
client.connect({onSuccess:onConnect});//連線伺服器並註冊連線成功處理事件
function onConnect() {
console.log("onConnected");
client.subscribe("World");//訂閱主題
}
client.onConnectionLost = onConnectionLost;//註冊連線斷開處理事件
client.onMessageArrived = onMessageArrived;//註冊訊息接收處理事件
function onConnectionLost(responseObject) {
console.log(responseObject)
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
console.log("連線已斷開");
}
}
function onMessageArrived(message) {
console.log("收到訊息:"+message.payloadString);
}
//傳送訊息
// message = new Paho.MQTT.Message("hello");
// message.destinationName = "/topic";
// client.send(message);
</script>