MQTT服务器/MQTT_C#客户端/Websoket连MQTT

在这里插入图片描述
MQTT(消息队列遥测传输)是ISO 标准(ISO/IEC PRF 20922)下基于发布/订阅范式的消息协议。它工作在 TCP/IP协议族上,是为硬件性能低下的远程设备以及网络状况糟糕的情况下而设计的发布/订阅型消息协议,为此,它需要一个消息中间件 。
MQTT是一个基于客户端-服务器的消息发布/订阅传输协议。MQTT协议是轻量、简单、开放和易于实现的,这些特点使它适用范围非常广泛。在很多情况下,包括受限的环境中,如:机器与机器(M2M)通信和物联网(IoT)。其在,通过卫星链路通信传感器、偶尔拨号的医疗设备、智能家居、及一些小型化设备中已广泛使用。

1 . 搭建MQTT服务器

找到上传中的 emqx-5.3.2-windows-amd64 打开bin如下:
链接: emqx-5.3.2-windows-amd64
安装后会在服务中有一个emqx_5.3.2的服务
如果安装失败 在上传中找到链接: VC_redist.x64.exe 安装。
正确后在浏览器输入 http://127.0.0.1:18083 会有如下mqtt服务端管理页面:
在这里插入图片描述
进入客户端认证,创建一个服务端池。里面设置用户名密码。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
c# 中 mqtt 客户端端口用 ip :1883
websoket 端口用 8083

c# 客户端连接

管理NuGet程序包 添加mqttnet
管理NuGet程序包 添加mqttnet
界面
在这里插入图片描述

using MQTTnet;
using MQTTnet.Core;
using MQTTnet.Core.Client;
using MQTTnet.Core.Packets;
using MQTTnet.Core.Protocol;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private MqttClient mqttClient = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {}


        //连接方法
        private async Task ConnectMqttServerAsync()
        {
            if (mqttClient == null)
            {
                mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient;//创建客户端
                mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;//接收订阅数据
                mqttClient.Connected += MqttClient_Connected;//连接成功后
                mqttClient.Disconnected += MqttClient_Disconnected;//连接不成功
            }

            try
            {
                var options = new MqttClientTcpOptions
                {
                    Server = textBox5.Text,// "172.16.6.133",
                    Port =Convert.ToInt32(textBox7.Text),// 1883,
                    ClientId = Guid.NewGuid().ToString().Substring(0, 5),//这个只要不重复就行
                    UserName = textBox3.Text,// "yado",
                    Password = textBox6.Text // "yado123"
                };
                await mqttClient.ConnectAsync(options);//根据参数连接
            }
            catch (Exception ex)
            {
                Invoke((new Action(() => {
                    txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
                })));
            }
        }

        //成功连接回调
        private void MqttClient_Connected(object sender, EventArgs e)
        {
            Invoke((new Action(() => {
                txtReceiveMessage.AppendText("已连接到MQTT服务器!" + Environment.NewLine);
            })));
        }

        //断开回调
        private void MqttClient_Disconnected(object sender, EventArgs e)
        {
            Invoke((new Action(() => {
                txtReceiveMessage.AppendText("已断开MQTT连接!" + Environment.NewLine);
            })));
        }

        //接收到订阅消息
        private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            Invoke((new Action(() => {
                txtReceiveMessage.AppendText($">> {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
            })));
        }

        //点击连接
        private void button3_Click(object sender, EventArgs e)
        {
            Task.Run(async () => { await ConnectMqttServerAsync(); });
        }

        //发布主题
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string topic = textBox1.Text.Trim();
                if (string.IsNullOrEmpty(topic))
                {
                    MessageBox.Show("发布主题不能为空!");
                    return;
                }
                string inputString = textBox2.Text.Trim();
                var appMsg = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(inputString), MqttQualityOfServiceLevel.AtMostOnce, false);
                mqttClient.PublishAsync(appMsg);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
        //订阅
        private void button2_Click(object sender, EventArgs e)
        {
            string topic = textBox4.Text.Trim();

     
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个基于Java的WebSocket连接MQTT服务器的代码示例: ```java import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.Base64; import java.util.concurrent.CountDownLatch; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.eclipse.paho.client.mqttv3.util.Debug; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; public class MqttWebSocketClient { private static final String MQTT_BROKER_URI = "wss://mqtt.example.com"; private static final String MQTT_CLIENT_ID = "mqtt-websocket-client"; private static final String MQTT_USERNAME = "your-username"; private static final String MQTT_PASSWORD = "your-password"; public static void main(String[] args) { try { // Create a WebSocket client and connect to the MQTT broker WebSocketClient webSocketClient = new WebSocketClient(new URI(MQTT_BROKER_URI)) { @Override public void onOpen(ServerHandshake handshake) { System.out.println("WebSocket connection established"); } @Override public void onMessage(String message) { System.out.println("Received message: " + message); } @Override public void onMessage(ByteBuffer message) { // Convert the binary message to a string and print it byte[] bytes = new byte[message.remaining()]; message.get(bytes); String str = Base64.getEncoder().encodeToString(bytes); System.out.println("Received binary message: " + str); } @Override public void onClose(int code, String reason, boolean remote) { System.out.println("WebSocket connection closed: " + reason); } @Override public void onError(Exception ex) { System.out.println("WebSocket connection error: " + ex.getMessage()); } }; webSocketClient.connect(); // Wait for the WebSocket connection to be established CountDownLatch latch = new CountDownLatch(1); while (!webSocketClient.isOpen()) { latch.await(); } // Create an MQTT client and connect to the broker over the WebSocket MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setUserName(MQTT_USERNAME); connectOptions.setPassword(MQTT_PASSWORD.toCharArray()); MqttClient mqttClient = new MqttClient(MQTT_BROKER_URI, MQTT_CLIENT_ID, new MemoryPersistence()); mqttClient.setCallback(new MqttCallbackHandler()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }, null); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); connectOptions.setSocketFactory(sslSocketFactory); Debug clientDebug = mqttClient.getDebug(); clientDebug.dumpClient(); mqttClient.connect(connectOptions); // Subscribe to a topic and publish a message mqttClient.subscribe("test/topic"); mqttClient.publish("test/topic", new MqttMessage("Hello, MQTT over WebSocket!".getBytes())); // Wait for the MQTT message to be received latch.await(); // Disconnect from the broker and close the WebSocket client mqttClient.disconnect(); webSocketClient.close(); } catch (URISyntaxException | InterruptedException | MqttException | Exception ex) { System.out.println("Exception: " + ex.getMessage()); } } private static class MqttCallbackHandler implements org.eclipse.paho.client.mqttv3.MqttCallback { @Override public void connectionLost(Throwable cause) { System.out.println("MQTT connection lost: " + cause.getMessage()); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { System.out.println("Received MQTT message: " + new String(message.getPayload())); } @Override public void deliveryComplete(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken token) { System.out.println("MQTT message delivered: " + token.getMessageId()); } } } ``` 在上面的代码中,我们使用了Java WebSocket API(`org.java_websocket`)来创建WebSocket客户端,并使用Eclipse Paho MQTT客户端库来连接到MQTT服务器。在`main`方法中,我们首先创建一个`WebSocketClient`来连接到MQTT经纪人的WebSocket端点。然后,我们等待WebSocket连接建立,然后创建一个`MqttClient`并使用`MqttConnectOptions`进行连接。我们还使用了一个自定义的`MqttCallbackHandler`来处理MQTT消息。最后,我们订阅一个主题并发布一条消息。在等待MQTT消息时,我们使用一个`CountDownLatch`来阻止主线程退出。在收到MQTT消息后,我们减少`CountDownLatch`的计数器并退出阻塞状态。最后,我们断开与MQTT服务器的连接并关闭WebSocket客户端

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值