In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the knowledge of "how to use WebSocket to connect to a MQTT server". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
In recent years, with the rapid development of Web front-end, new features of browsers emerge one after another, and more and more applications can be realized through browser rendering engine on the browser side. Therefore, WebSocket, an instant messaging method of Web applications, has been widely used.
WebSocket is a protocol for full-duplex communication over a single TCP connection. The WebSocket communication protocol was defined as the standard RFC 6455 by IETF in 2011 and supplemented by RFC 7936. WebSocket API is also defined as a standard by the W3C.
WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In WebSocket API, only one handshake is needed between the browser and the server, and a persistent connection can be directly created between the browser and the server for two-way data transmission.
Compare Paho.mqtt.js between the two clients
Paho is a MQTT client project for Eclipse, and Paho JavaScript Client is one of the browser-based libraries that uses WebSockets to connect to the MQTT server. Compared with another JavaScript connection library, it has fewer functions and is not recommended.
MQTT.js
MQTT.js is a fully open source client library for the MQTT protocol, written in JavaScript, and available for Node.js and browsers. On the Node.js side, you can use command line connections through global installation, and support MQTT/TCP, MQTT/TLS and MQTT/WebSocket connections. It is worth mentioning that MQTT.js also has good support for WeChat Mini Programs.
This article will use the MQTT.js library to explain how to connect to WebSocket.
Install MQTT.js
If the reader has a Node.js running environment on his machine, you can install MQTT.js directly using the npm command.
Install the npm install mqtt-saveCDN reference in the current directory
Or use the CDN address directly without installation
/ / globally initialize a mqtt variable console.log (mqtt) to connect to the MQTT server
This article will use the free public MQTT server provided by EMQ X, which is based on EMQ X's MQTT Internet of things cloud platform. The server access information is as follows:
Broker: broker.emqx.io
TCP Port: 1883
Websocket Port: 8083
EMQ X uses port 8083 for normal connections and 8084 for WebSocket connections on SSL.
For simplicity, let's put the subscriber and publisher in the same file:
Const clientId = 'mqttjs_' + Math.random (). ToString (16) .substr (2, 8) const host =' ws://broker.emqx.io:8083/mqtt'const options = {keepalive: 60, clientId: clientId, protocolId: 'MQTT', protocolVersion: 4, clean: true, reconnectPeriod: 1000, connectTimeout: 30 * 1000, will: {topic:' WillMsg', payload: 'Connection Closed normalization.. examples, qos: 0, retain: false} } console.log ('Connecting mqtt client') const client = mqtt.connect (host, options) client.on (' error', (err) = > {console.log ('Connection error:', err) client.end ()}) client.on ('reconnect', () = > {console.log (' Reconnecting...')})
The connection address demonstrated above can be split into: ws: / / broker. Emqx.io: 8083 / mqtt
That is, the protocol / / host name. Domain name: Port / path
Beginners are prone to the following mistakes:
The connection address does not specify the protocol: WebSocket, as a communication protocol, uses ws (non-encrypted) and wss (SSL encryption) as the protocol identity. The MQTT.js client supports multiple protocols, and the connection address should specify the protocol type.
The connection address does not specify the port: MQTT does not specify the WebSocket access port, and 8083 8084 is used by default on EMQ X as the unencrypted connection and the encrypted connection port, respectively. The default port of WebSocket protocol is the same as that of HTTP. If the port is not filled in, it means that the default port connection of WebSocket is used. When using a standard MQTT connection, there is no need to specify a port. For example, MQTT.js can use mqtt://localhost to connect to the standard MQTT 1883 port on the Node.js side, and connect to port 8884 when the connection address is mqtts://localhost.
No path to the connection address: MQTT-WebSoket uniformly uses / path as the connection path, which should be specified when connecting. The path used on EMQ X is / mqtt.
The protocol does not match the port: using a wss connection but connecting to port 8083
Using unencrypted WebSocket connections under HTTPS: while promoting HTTPS, institutions such as Google also impose security restrictions through browser constraints, that is, browsers automatically prohibit the use of unencrypted ws protocols to initiate connection requests under HTTPS connections.
The certificate does not match the connection address: it is long. For more information, please see EMQ enabling SSL/TLS encrypted connection below.
Connection option
In the above code, options is the client connection option. The following is the description of the main parameters. For more information, please see https://www.npmjs.com/package/mqtt#connect.
Keepalive: heartbeat time. Default is 60 seconds. Set 0 to disable.
ClientId: client ID, generated randomly via 'mqttjs_' + Math.random () .toString (16) .substr (2,8) by default
Username: connection user name (optional)
Password: connection password (optional)
Clean:true, set to false to receive QoS 1 and 2 messages when offline
ReconnectPeriod: default is 1000 milliseconds, the interval between two reconnections, client ID duplicates, authentication failure and other clients will reconnect.
ConnectTimeout: the default is 30 * 1000 milliseconds, the waiting time before receiving the CONNACK, that is, the connection timeout
Will: a testamentary message that Broker will send automatically when the client is severely disconnected. The general format is:
Topic: topics to publish
Payload: message to publish
Qos:QoS
Retain: reserved Fla
Subscribe / unsubscribe
Subscriptions cannot be made until the connection is successful, and the subscribed topics must comply with the MQTT subscription topic rules
Note the asynchronous non-blocking nature of JavaScript. Only after the connect event can you ensure that the client has successfully connected, or determine whether the connection is successful by client.connected:
Client.on ('connect', () = > {console.log (' Client connected:' + clientId) / / Subscribe client.subscribe ('testtopic', {qos: 0})}) / / Unsubscribeclient.unubscribe (' testtopic', () = > {console.log ('Unsubscribed')}) publish / receive messages
If you publish a message to a topic, the published topic must comply with the MQTT publishing theme rules, otherwise the connection will be disconnected. You do not need to subscribe to this topic before publishing, but make sure that the client has successfully connected:
/ / Publishclient.publish ('testtopic',' ws connection demotion, {qos: 0, retain: false}) / / Receivedclient.on ('message', (topic, message, packet) = > {console.log (' Received Message:'+ message.toString () +'\ nOn topic:'+ topic)}) WeChat Mini Programs
The MQTT.js library has special treatment for WeChat Mini Programs, using wxs protocol identifiers. Note that the Mini Program development specification requires that encrypted connections must be used and the connection address should be similar to wxs://broker.emqx.io:8084/mqtt.
EMQ X enables SSL/TLS encrypted connection
EMQ has a built-in self-signed certificate, and an encrypted WebSocket connection has been started by default, but most browsers will report invalid certificate errors such as net::ERR_CERT_COMMON_NAME_INVALID (Chrome, 360and other webkit kernel browsers in developer mode, the Console tab can view most connection errors). The reason for this error is that the browser cannot verify the validity of the self-signed certificate. The reader needs to purchase a trusted certificate from the certificate authority and refer to the appropriate section of this article for configuration: the EMQ X MQTT server enables SSL/TLS secure connections.
The requirements for enabling SSL/TLS certificates are summarized as follows:
Bind the domain name to the public network address of the MQTT server: the certificate signed by the CA institution is for the domain name
Apply for a certificate: apply to the CA institution for the certificate of the domain name used, pay attention to select a reliable CA institution and the certificate should distinguish between the pan-domain name and the host name
Select wss protocol when using encrypted connection and use domain name connection: after binding the domain name-certificate, you must use the domain name instead of the IP address to connect, so that the browser will verify the certificate against the domain name to establish a connection after passing the verification.
EMQ X configuration
Open the etc/emqx.conf configuration file and modify the following configuration:
# wss snooping address listener.wss.external = 808 modify key file address listener.wss.external.keyfile = etc/certs/cert.key# modify certificate file address listener.wss.external.certfile = etc/certs/cert.pem
Restart EMQ X when you are finished.
You can use your certificate and key file to replace it directly under etc/certs/.
Configure reverse proxy and certificate on Nginx
Using Nginx to reverse proxy and encrypt WebSocket can reduce the computing pressure of EMQ X server and realize domain name reuse at the same time. At the same time, multiple back-end service entities can be allocated through Nginx load balancing.
# it is recommended that WebSocket also bind to port 443 listen 443,8084 example.com;ssl on;ssl_certificate / etc/cert.crt; # certificate path ssl_certificate_key / etc/cert.key; # key path # upstream server list upstream emq_server {server 10.10.1.1example.com;ssl on;ssl_certificate 8883 weight=1; server 10.10.1.2 weight=1; server 10.10.1.3Ze8883 weight=1 } # ordinary website application location / {root www; index index.html;} # reverse proxy to EMQ X unencrypted WebSocketlocation / {proxy_redirect off; # upstream proxy_pass http://emq_server; proxy_set_header Host $host; # reverse proxy retains the client address proxy_set_header X-Real_IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr:$remote_port # WebSocket additional request header proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";} "how to connect to a MQTT server using WebSocket" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.