Eclipse Mosquitto 是一套開放原始碼的 MQTT Broker。
在 openSUSE 安裝:
sudo zypper in mosquitto
如果要執行的話,使用 systemctl 啟動服務:
sudo systemctl start mosquitto
再來使用 tcl.mqttc 驗證是否可以正確連線。
Subscribe:
package require mqttc
mqttc client "tcp://localhost:1883" "USERSSub" 1 -cleansession 1
client subscribe "MQTT Examples" 1
while 1 {
if {[catch {set result [client receive]}]} {
puts "Receive error!!!"
break
}
if {[llength $result] > 0} {
puts "[lindex $result 0] - [lindex $result 1]"
if {![string compare -nocase [lindex $result 1] "Exit"]} {
break
}
}
}
client unsubscribe "MQTT Examples"
client close
Publish:
package require mqttc
mqttc client "tcp://localhost:1883" "USERSPub" 1 -timeout 1000
client publishMessage "MQTT Examples" "Hello MQTT!" 1 0
client publishMessage "MQTT Examples" "Exit" 1 0
client close
先執行 Subscribe 的部份,再使用 Publish 發送訊息,確定可以正確執行。
下面是另外一個使用 tcl.mqttc 測試 Subscribe 與 Publish 功能的測試程式:
package require Thread
package require mqttc
catch {console show}
set ::gThread [thread::create {thread::wait} ]
set result 0
proc subscribe { } {
thread::send -async $::gThread {
package require mqttc
mqttc client "tcp://localhost:1883" "USERTest1" 1 -cleansession 1
client subscribe "MQTT Examples" 1
while 1 {
if {[catch {set result [client receive]}]} {
puts "Receive error!!!"
break
}
if {[llength $result] > 0} {
puts "[lindex $result 0] - [lindex $result 1]"
if {![string compare -nocase [lindex $result 1] "Exit"]} {
break
}
}
}
client unsubscribe "MQTT Examples"
client close
} ::result
}
subscribe
puts "started test..."
after 250
mqttc client "tcp://localhost:1883" "USERTest2" 1 -timeout 1000
client publishMessage "MQTT Examples" "Hello MQTT!" 1 0
client publishMessage "MQTT Examples" "Exit" 1 0
client close
vwait ::result
沒有留言:
張貼留言