MQTT over WebSocket: What It Is and How It Works
MQTT messages using the WebSocket protocol, which works well in web browsers and firewalls. It combines MQTT's lightweight messaging with WebSocket's ability to keep a connection open over HTTP ports, enabling real-time communication in web apps.How It Works
Imagine you want to chat with a friend using a walkie-talkie (MQTT), but you are inside a building where walkie-talkie signals don't pass well. Instead, you use the building's phone system (WebSocket) to talk. MQTT over WebSocket works similarly by sending MQTT messages through a WebSocket connection, which uses standard web ports like 80 or 443.
This means devices or web browsers can keep a constant connection open to a server, sending and receiving MQTT messages in real time without being blocked by firewalls or needing special network setups. WebSocket acts like a tunnel inside the usual web traffic, carrying MQTT messages smoothly.
Example
This example shows how to connect to an MQTT broker over WebSocket using JavaScript in a web browser.
import mqtt from 'mqtt/dist/mqtt.min.js'; const client = mqtt.connect('wss://test.mosquitto.org:8081/mqtt'); client.on('connect', () => { console.log('Connected to MQTT broker over WebSocket'); client.subscribe('test/topic'); client.publish('test/topic', 'Hello MQTT over WebSocket!'); }); client.on('message', (topic, message) => { console.log(`Received message on ${topic}: ${message.toString()}`); });
When to Use
Use MQTT over WebSocket when you want MQTT messaging inside web browsers or environments where direct MQTT connections are blocked by firewalls. It is ideal for real-time web apps, dashboards, or IoT devices that communicate through standard web ports.
For example, a smart home dashboard running in a browser can use MQTT over WebSocket to receive sensor updates instantly without extra network setup. It also helps when deploying IoT solutions in corporate networks with strict firewall rules.
Key Points
- MQTT is a lightweight messaging protocol for IoT.
- WebSocket enables full-duplex communication over HTTP ports.
- MQTT over WebSocket combines both to work inside web browsers and firewalls.
- It uses standard web ports (80, 443) to avoid network blocks.
- Commonly used in web apps and IoT dashboards for real-time updates.