鉴于网上VB.Net实现MQTT通信示例几乎没有,本人参考C#范例编写一版VB.Net客户端范例以作参考,已通过和服务器端的订阅和发布消息测试,只需要声明实例类之后调用Init代码即可启动,可实现断线自动重连。由于服务器端启用了TLS所以在连接参数里专门设置了一下,Topic将中文替换为需要发布或订阅的标题即可,Publish的数据需要根据需求再单独处理,直接上代码。
Imports System.Text
Imports System.Threading
Imports MQTTnet
Imports MQTTnet.Client
Imports MQTTnet.Client.Options
Imports System.IO
Imports MQTTnet.Client.Connecting
Imports MQTTnet.Client.Disconnecting
Public Class MQTT
Private WRThread As Thread 'MQTT线程
Private m_Host As String
Private m_Port As Integer
Private GatewayData(36) As Byte
Private IsConnected As Boolean
Private mqttFactory = New MqttFactory()
Private mqttClient As IMqttClient
Public Sub Init(host As String, port As Integer)
m_Host = host
m_Port = port
'启动WRThread线程
WRThread = New Thread(AddressOf WriteAndRead) With {.IsBackground = True}
WRThread.Start()
End Sub
Public Sub WriteAndRead(stateInfo As Object)
While (True)
Try
If IsConnected Then
'发布
Dim applicationMessage = New MqttApplicationMessageBuilder().WithTopic("发布标题").WithPayload(GatewayData).Build
mqttClient.PublishAsync(applicationMessage, CancellationToken.None)
Else
'建立连接
If My.Computer.Network.Ping(m_Host) Then
mqttClient = mqttFactory.CreateMqttClient()
'绑定事件
mqttClient.UseApplicationMessageReceivedHandler(AddressOf MqttApplicationMessageReceived)
mqttClient.UseConnectedHandler(AddressOf MqttConnected)
mqttClient.UseDisconnectedHandler(AddressOf MqttDisconnected)
'连接
Dim mqttClientOptions = New MqttClientOptionsBuilder().WithTcpServer(m_Host, m_Port).WithTls(New MqttClientOptionsBuilderTlsParameters With {.UseTls = True, .AllowUntrustedCertificates = True}).Build()
mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None)
End If
End If
Thread.Sleep(5000)
Catch ex As Exception
Thread.Sleep(5000)
End Try
End While
End Sub
Private Sub MqttConnected(ByVal e As MqttClientConnectedEventArgs)
IsConnected = True
'订阅
Dim mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder.WithTopicFilter("订阅标题").Build
mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None)
End Sub
Private Sub MqttDisconnected(ByVal e As MqttClientDisconnectedEventArgs)
IsConnected = False
End Sub
Private Sub MqttApplicationMessageReceived(ByVal e As MqttApplicationMessageReceivedEventArgs)
Try
Dim Topic As String = e.ApplicationMessage.Topic
Dim QoS As String = e.ApplicationMessage.QualityOfServiceLevel.ToString()
Dim Retained As String = e.ApplicationMessage.Retain.ToString()
'Dim text As String = Encoding.UTF8.GetString(e.ApplicationMessage.Payload)
Dim text As String
text = e.ApplicationMessage.Payload(0)
For i As Integer = 1 To e.ApplicationMessage.Payload.Length - 1
text += ("," + e.ApplicationMessage.Payload(i).ToString)
Next
File.AppendAllText("D:\MQTTSubscribe.txt", Now() & "," & "Topic:" & Topic & ";QoS:" & QoS & ";Retained:" & Retained & ";Payload:" & text & vbNewLine)
Catch exp As Exception
File.AppendAllText("D:\MQTTSubscribe.txt", Now() & "," & "Exception:" & exp.Message & vbNewLine)
End Try
End Sub