What is the difference between MQTT and WebSocket?
Answer
Overview
MQTT and WebSocket are both used for real-time communication, but they serve different purposes. MQTT is a lightweight messaging protocol designed for IoT, while WebSocket is a full-duplex communication protocol for real-time web applications.
MQTT (Message Queuing Telemetry Transport)
MQTT is a publish-subscribe messaging protocol built for constrained devices and low-bandwidth networks. It requires a broker (server) that routes messages between publishers and subscribers.
dart// Flutter MQTT using mqtt_client package import 'package:mqtt_client/mqtt_client.dart'; import 'package:mqtt_client/mqtt_server_client.dart'; final client = MqttServerClient('broker.hivemq.com', 'flutter_client'); client.port = 1883; client.keepAlivePeriod = 60; await client.connect(); // Subscribe to a topic client.subscribe('sensors/temperature', MqttQos.atLeastOnce); // Publish a message final builder = MqttClientPayloadBuilder(); builder.addString('{"temp": 25.5}'); client.publishMessage('sensors/temperature', MqttQos.atLeastOnce, builder.payload!); // Listen for messages client.updates!.listen((List<MqttReceivedMessage<MqttMessage>> messages) { final message = messages[0].payload as MqttPublishMessage; final payload = MqttPublishPayload.bytesToStringAsString(message.payload.message); print('Received: $payload'); });
WebSocket
WebSocket provides a persistent, full-duplex TCP connection between client and server. Communication is bidirectional — both sides can send messages anytime without a broker.
dart// Flutter WebSocket using web_socket_channel package import 'package:web_socket_channel/web_socket_channel.dart'; final channel = WebSocketChannel.connect( Uri.parse('wss://echo.websocket.events'), ); // Send a message channel.sink.add('Hello Server!'); // Listen for messages channel.stream.listen( (message) => print('Received: $message'), onError: (error) => print('Error: $error'), onDone: () => print('Connection closed'), ); // Close connection channel.sink.close();
Key Differences
| Feature | MQTT | WebSocket |
|---|---|---|
| Protocol Type | Application-layer messaging protocol | Transport-layer communication protocol |
| Pattern | Publish-Subscribe (via broker) | Bidirectional point-to-point |
| Broker Required | Yes (e.g., Mosquitto, HiveMQ) | No (direct client-server) |
| Header Overhead | 2-5 bytes (extremely lightweight) | 2-14 bytes per frame |
| QoS Levels | 3 levels (0, 1, 2) | None (relies on TCP) |
| Offline Support | Yes (broker queues messages) | No (connection must be active) |
| Scalability | Excellent (millions of devices) | Moderate (resource per connection) |
| Best For | IoT, sensors, M2M | Chat apps, live dashboards, gaming |
MQTT QoS Levels
| QoS Level | Name | Guarantee | Use Case |
|---|---|---|---|
| QoS 0 | At most once | Fire and forget | Sensor data (non-critical) |
| QoS 1 | At least once | Delivered, may duplicate | General IoT messaging |
| QoS 2 | Exactly once | 4-step handshake, no duplicates | Financial/critical data |
MQTT Over WebSocket
MQTT can run over WebSocket to work through web browsers and firewalls:
dart// MQTT over WebSocket in Flutter final client = MqttServerClient.withPort( 'ws://broker.hivemq.com', 'flutter_ws_client', 8000, ); client.useWebSocket = true; await client.connect();
When to Use Which
- Use MQTT for IoT projects, sensor networks, home automation, or any scenario with constrained devices and unreliable networks
- Use WebSocket for real-time web apps like chat, live notifications, collaborative editing, or gaming
- Use MQTT over WebSocket when you need MQTT's pub-sub model through web browsers or corporate firewalls
Key Insight: MQTT and WebSocket are complementary, not competing. MQTT is a messaging protocol (defines how messages are routed), while WebSocket is a transport protocol (defines how data is transmitted). You can use both in the same Flutter project.