What is the difference between MQTT and WebSocket?

#flutter#mqtt#websocket#iot#real-time#networking

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

FeatureMQTTWebSocket
Protocol TypeApplication-layer messaging protocolTransport-layer communication protocol
PatternPublish-Subscribe (via broker)Bidirectional point-to-point
Broker RequiredYes (e.g., Mosquitto, HiveMQ)No (direct client-server)
Header Overhead2-5 bytes (extremely lightweight)2-14 bytes per frame
QoS Levels3 levels (0, 1, 2)None (relies on TCP)
Offline SupportYes (broker queues messages)No (connection must be active)
ScalabilityExcellent (millions of devices)Moderate (resource per connection)
Best ForIoT, sensors, M2MChat apps, live dashboards, gaming

MQTT QoS Levels

QoS LevelNameGuaranteeUse Case
QoS 0At most onceFire and forgetSensor data (non-critical)
QoS 1At least onceDelivered, may duplicateGeneral IoT messaging
QoS 2Exactly once4-step handshake, no duplicatesFinancial/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.