C 整合MQTT 發布 訂閱

2021-10-21 06:20:19 字數 3598 閱讀 9506

服務端

服務端是乙個控制台應用

using mqttnet;

using mqttnet.core.adapter;

using mqttnet.core.diagnostics;

using mqttnet.core.protocol;

using mqttnet.core.server;

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.threading;

using system.threading.tasks;

namespace testmqttserver

else

if(inputstring ==

"clients"

|| inputstring ==

"c")

,協議版本:");

}}else

]無效");

}}}private

static

void

startmqttserver()

}return mqttconnectreturncode.connectionaccepted;}}

; mqttserver =

newmqttserve***ctory()

.createmqttserver

(option)

as mqttserver;

mqttserver.clientconnected +

= mqttserver_clientconnected;

mqttserver.clientdisconnected +

= mqttserver_clientdisconnected;

}catch

(exception e)

} mqttserver.

startasync()

; console.

writeline

("mqtt伺服器啟動成功");

}private

static

void

mqttserver_clientdisconnected

(object sender,

mqttclientdisconnectedeventargs e)

]斷開連線");

}private

static

void

mqttserver_clientconnected

(object sender,

mqttclientconnectedeventargs e)

]已連線,協議版本:");

}private

static

void

(object sender,

private

static

void

mqttnettrace_tracemessagepublished

(object sender,

mqttnettracemessagepublishedeventargs e)

}}

客戶端

($"已訂閱主題"

+environment.newline)

; txtsubtopic.enabled =

false

; btnsubscribe.enabled =

false;}

private

void

btnpublish_click

(object sender,

eventargs e)

string inputstring = txtsendmessage.text.

trim()

;new

(topic,encoding.utf8.

getbytes

(inputstring)

,mqttqualityofservicelevel.atmostonce,

false);

mqttclient.

publishasync;}

}}測試

服務端

客戶端

通過 C 實現 MQTT 的訂閱和發布

第三步 執行 第二部分 單向認證模式 第四步 執行 本章節主要介紹用c 實現mqtt的訂閱和發布。分為 無加密模式 和 單向認證模式。測試環境為本機。準備工作 保持安裝後預設配置即可 visual studio中新建控制台應用程式normalpublisher,新增m2mqtt引用。program類...

python 連線mqtt發布和訂閱資訊

pip install paho mqttimport paho.mqtt.client as mqtt import json import time host 127.0.0.1 mqtt伺服器位址 port 1883 client id 101 客戶端id,自己設定 同時訂閱多個主題方式使用 ...

基於MQTT的訊息發布訂閱python實現

mqtt 全稱為 message queuing telemetry transport 訊息佇列遙測傳輸 是一種基於發布 訂閱正規化的 輕量級 訊息協議。該協議構建於tcp ip協議上。mqtt協議是輕量 簡單 開放和易於實現的,這些特點使它適用範圍非常廣泛。在很多情況下,包括受限的環境中,如 機...