Briefly introduce EMQX
1. EMQX is an open source distributed Internet of Things (MQTT) message server. It is a high-performance, high-reliability messaging middleware for connecting and transmitting data between IoT devices.
2. EMQX provides a complete implementation of the MQTT protocol, and supports large-scale device connections, message publishing/subscribing, device management, and data routing. It is horizontally scalable, can easily handle millions of simultaneously connected devices, and provides reliable and low-latency messaging.
3. EMQX also provides a wealth of functions, such as device authentication, message persistence, QoS (Quality of Service) control, failover, clustering and data analysis, etc. It can be used to build various IoT applications, such as smart home, industrial automation, smart transportation, etc.
The above are some official introductions. In fact, the main function of EMQX is to realize real-time communication, and this technology is widely used in Internet of Things projects. Most of the hardware communication protocols are tcp, and most of the software are http or https, so Well, real-time communication can be realized by using the middleware of EMQX
It can also be better understood through this picture. As long as the topic subscribed by the subscriber is consistent with the topic of the publisher, the subscriber can receive the message, and the subscriber is not just one, but hundreds of thousands. I The following will also demonstrate the effect of multi-terminal subscription. In fact, using EMQX to realize this function is not only mqtt, but also QUIC and WebSocket. Here I introduce one, and the others can be integrated in the same way.
Install EMQX
First of all, we need to install EMQX on our computer
This is the download URL: Download EMQX
Just download it according to the guide in the picture below, choose your own operating system and version, click download and unzip it. (I downloaded version 5.1, and the client interface of each version may be slightly different)
Follow its instructions and enter the following directory
Enter cmd in it and press Enter
Enter this command emqx start
Then open the task manager and see that this process proves that we have successfully started
Then enter this URL in your browser: http://localhost:18083/
The initial account password for the first login is: admin public
After logging in, he will ask you to change your password, just change it to something easy to remember
This is the interface of the management panel, where you can see how many users are connected
Note that after we start the emqx service here, it means that we are a server, which means that we are a transfer station, which is what is shown in this picture
Next, you can go to the Vue project and edit the code in Nodejs
Connect EMQX with mqtt in Vue
1. First install mqtt in the Vue project
npm i mqtt --save
2. Introduce mqtt.js in the component
import mqtt from 'mqtt/dist/mqtt'
3. Write the method of connecting mqtt in methods and call this method in the mounted life cycle
initMqtt() {
// 连接配置选项
let options = {
connectTimeout: 4000, // 超时时间
// 认证信息
clientId: '111', //不填默认随机生成一个ID
username: 'admin', //用户名
password: '123456' //密码
}
this.client = mqtt.connect('ws://localhost:8083/mqtt', options) //调用连接的api
//连接成功
this.client.on('connect', (e) => {
console.log('连接成功', e)
})
//重连提醒
this.client.on('reconnect', (error) => {
console.log('正在重连', error)
})
//连接失败提醒
this.client.on('error', (error) => {
console.log('连接失败', error)
})
}
In the above code, options
it is the client connection option, the following is the description of the main parameters, and the detailed parameters can be seen: mqtt - npm .
-
keepalive: heartbeat time, the default is 60 seconds, set to 0 to disable;
-
clientId: Client ID, which is randomly
'mqttjs_' + Math.random().toString(16).substr(2, 8)
generated by default; -
username: connection username (if any);
-
password: the connection password (if any);
-
clean: true, set to false to receive QoS 1 and 2 messages while offline;
-
reconnectPeriod: The default is 1000 milliseconds, the interval between two reconnections, the client will reconnect if the client ID is repeated, the authentication fails, etc.;
-
connectTimeout: The default is 30 * 1000 milliseconds, the waiting time before receiving CONNACK, that is, the connection timeout time.
In our management panel, we can see that the connection with id: 111 is successful
Note that this address: ws://localhost:8083/mqtt is the default address to connect to the EMQX server opened in our computer. Of course, if it is opened as a server in other places, you can modify the address here.
When we connect successfully, we can see that the client object in mqtt is mounted on the Vue instance, and then we can directly use this to call the method on it
Every time we want to update the page, we must disconnect the connection with mqtt in time, otherwise there will be repeated connections. We can choose a lifecycle hook function when the component is destroyed to disconnect. Here I use :beforeDestroy
// 在组件销毁之前与mqtt断开连接
beforeDestroy() {
//断开连接
this.client.end()
this.client = null
console.log('已经与mqtt客户端断开连接')
}
4. Subscribe to a single message
We can write a method of subscribing to a single message in methods, which can be called after the mqtt connection
//订阅一个信息
subscribe() {
const str = 'setM3'
this.client.subscribe(str, { qos: 0 }, (err) => {
if (!err) {
console.log(`主题为:“${str}” 的消息订阅成功`)
} else {
console.log('消息订阅失败')
}
})
},
In the console, you can see that the subscription has been successful
5. Subscribe to multiple messages
//订阅多个信息
subscribes() {
const arr = ['setM2', 'setM3']
this.client.subscribe(arr, { qos: 1 }, (err) => {
if (!err) {
console.log(`主题为:“${arr}” 的消息订阅成功`)
} else {
console.log('消息订阅失败')
}
})
},
Here our multiple messages are subscribed successfully
6. Post a message
//发布信息
publish(topic, message) {
if (!this.client.connected) {
console.log('客户端未连接')
return
}
this.client.publish(topic, message, { qos: 0 }, (err) => {
if (!err) {
console.log(`主题为:${topic},内容为:${message} 发布成功`)
}
})
},
We can publish our message after subscribing to the message. Here is an example, we can embed this code in subscribing to a single message: It should be noted that we need to determine the topic and content of the message, and only subscribe to this topic Only people who will receive this data, and our message must meet the data in JSON format
this.publish('setM2', '{"data":"123"}')
You can see that the release has been successfully displayed in the console:
The reason why I can receive data here is because I also subscribed to setM2 before publishing, so I also received this data as a subscriber, and the function for receiving data is as follows
7. Receive messages
What needs to be noted here is that the messages we receive can only be published messages, and we cannot receive unpublished messages
//接收消息
receive() {
this.client.on('message', (topic, message) => {
console.log(`收到来自:${topic} 的消息:${message}`)
const data = JSON.parse(`${msg}`) //接受到控制信号的数据
console.log(data)
})
}
We use JSON.parse of js to convert it into an object, and then we can easily manipulate the data in it
We can call this method after publishing a message, and we can view the received message
Use mqtt to connect to EMQX on the node.js side
The code here is actually similar to that in vue, so I won’t analyze them one by one. After all, it’s all js code.
This is the mqtt connection configuration code: export it and use
const mqtt = require('mqtt')
//mqtt端口号:
// 1883 MQTT 协议端口
// 8883 MQTT/SSL 端口
// 8083 MQTT/WebSocket 端口
// 8080 HTTP API 端口
// 18083 Dashboard 管理控制台端口
// 连接选项
const options = {
clean: true, // true: 清除会话, false: 保留会话
connectTimeout: 4000, // 超时时间
// 认证信息
clientId: 'emqx_test',
username: 'admin',
password: '123456'
}
//ws://localhost:8083/mqtt
const connectUrl = 'ws://localhost:8083/mqtt'
const client = mqtt.connect(connectUrl, options) //建立连接
module.exports = client
Here's the other code:
const express = require('express')
const client = require('./mqtt')
const app = express()
client.on('connect', () => {
console.log('连接成功')
})
client.on('reconnect', (error) => {
console.log('正在重连:', error)
})
client.on('error', (error) => {
console.log('连接失败:', error)
})
//订阅setM3消息
client.subscribe('setM3', (err) => {
console.log('订阅setM3成功')
})
client.on('message', (topic, message) => {
const formattedTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
console.log('收到消息:', topic, message.toString())
const data = JSON.parse(message)
console.log(data)
})
app.listen(8080, () => {
console.log('api server running at http://127.0.0.1:8080')
})
Then run it on port 8080
You can see that our management panel already has two users at this time
In fact, in the management panel, we can also simulate user connection, configure the necessary options and id, etc. to connect
After the connection is completed, three users are connected at this time.
The topics subscribed by our Vue client are setM2 and setM3, and the topics subscribed by our nodejs server are setM3
Now we can send the corresponding data to this simulated user in the management panel, and then see if the other two users can receive the data
The data I simulated sending is as follows, the subject is setM3, the content is a JSON data, click publish
Both our client and server receive this data
Let's try to send data with the subject setM2 to see how it goes
It can be seen that the client can receive this request, but the server cannot receive this data because there is no subscription
Let's simulate the client to send data again. Before that, we can rewrite the code. The server subscribes to setM1, and the simulated user can also subscribe to setM1
This is the message sent by our client
this.publish('setM1', '{"data":"都看到这里了,给个三连不过分吧"}')
Our simulated user can receive data
The server can also
Seeing this, I believe you already have a certain understanding of emqx and mqtt, and you can use them basically. If you have any questions, you can comment or private message me at any time, and I will reply. Give me a three-link (crazy hint)