VB.Net实现客户端MQTT通信

鉴于网上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
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值