How MQTT Works over TCP, WebSockets, and TLS, and How CoAP Compares
This walkthrough uses captures from the late Nick Russo's free packet-capture library. They are in the IoT archive, iot_pcap.zip, under iot_pcap/: mqtt_unenc.pcapng, mqtt_unenc_ws.pcapng, mqtt_tls.pcapng, mqtt_tls_ws.pcapng, coap_get.pcapng, and coap_post_delete.pcapng. The archive is preserved by the Internet Archive, with the rest of the library listed on his job aid page. We decoded the captures with VisualEther, which turns a Wireshark PCAP into a sequence diagram with a plain-English caption on every message.
MQTT is the messaging protocol behind much of the Internet of Things. A sensor, a smart plug, or a Home Assistant server connects to a central server called a broker and publishes readings to named topics, such as home/kitchen/temperature. Anything subscribed to that topic gets each reading as it arrives. Zigbee2MQTT, Tasmota, and most cloud IoT services speak it.
The same MQTT session can travel four ways: over plain TCP, inside WebSocket so a web page can use it, inside TLS for encryption, or inside both. These captures record one client, the MQTT Explorer desktop app, doing the same thing all four ways against the public test broker test.mosquitto.org on November 29, 2020. Comparing them shows exactly what each layer adds and what an eavesdropper can still learn once TLS is on.
A fifth and sixth capture show CoAP, the other common IoT protocol. It does a similar job very differently: request and response over UDP, with no broker and no connection.
Four captures are drawn as annotated sequence diagrams:
- MQTT over TCP, port 1883: connect, subscribe, a burst of retained messages, and disconnect (74 frames).
- MQTT over WebSocket, port 8080: the same session behind an HTTP Upgrade (120 frames).
- MQTT over TLS 1.3, port 8883, without the session keys: only sizes and timing are visible (76 frames).
- CoAP GET requests over UDP, including separate responses, a block-wise transfer, and two errors (34 frames).
Each participant gets a lane, and each message is an arrow, numbered as in Wireshark and captioned with what it does. The three MQTT diagrams leave out some of the repeated statistics messages; the gaps in the frame numbers mark the cuts. Every diagram comes in three forms: an interactive viewer, an HTML page, and a printable PDF. In the viewer and the HTML page, clicking any message opens its full Wireshark field tree.
💡 Read the walkthrough and a diagram side by side: open the interactive diagram in a split-screen window, or open the HTML version in a new tab and snap the two windows side by side. Each capture section below links its own diagram.
MQTT in one minute
MQTT uses publish and subscribe. Clients never talk to each other directly; every message goes through the broker. A client publishes a message to a topic, a string with / separating its levels. The broker forwards it to every client whose subscription matches that topic. A subscription can use wildcards: + matches one level, and # matches all remaining levels, so home/# matches every topic under home/.
Every message has a quality of service (QoS) level:
- QoS 0, at most once: send and forget. TCP still delivers it reliably while the connection lasts.
- QoS 1, at least once: the receiver acknowledges with PUBACK, and the sender retransmits until it does.
- QoS 2, exactly once: a four-packet handshake removes duplicates.
A publisher can also ask the broker to retain a message. The broker keeps the last retained message on each topic and hands it to every new subscriber at once, so a dashboard that connects late still gets the latest value.
These captures use MQTT 3.1.1, an OASIS standard. Section numbers below refer to the 3.1.1 specification. The packets in these captures are:
| Packet | Direction | Job | Section |
|---|---|---|---|
| CONNECT | Client to broker | Open a session: protocol level, client ID, Keep Alive, flags | 3.1 |
| CONNACK | Broker to client | Accept or refuse the session | 3.2 |
| SUBSCRIBE | Client to broker | Ask for topics matching a filter | 3.8 |
| SUBACK | Broker to client | Grant a QoS level for each filter, or refuse it | 3.9 |
| PUBLISH | Either way | Carry one message on one topic | 3.3 |
| DISCONNECT | Client to broker | End the session cleanly | 3.14 |
Two more appear in most long-lived sessions but not here: PINGREQ and PINGRESP (3.12 and 3.13), the keepalive heartbeat a client sends when it has had nothing else to send for its Keep Alive interval.
Every MQTT packet starts with a fixed header: one byte for the packet type and flags, then a "remaining length" of one to four bytes. A DISCONNECT is just those two bytes, 0xE0 0x00. That small size is why MQTT suits slow or metered links.
What does each transport add to MQTT?
Here are all four MQTT captures side by side. Each one connects to test.mosquitto.org from the same client, about 95 ms away:
| TCP | WebSocket | TLS | TLS + WebSocket | |
|---|---|---|---|---|
| Capture | mqtt_unenc | mqtt_unenc_ws | mqtt_tls | mqtt_tls_ws |
| Broker port | 1883 | 8080 | 8883 | 8081 |
| Setup before CONNECT | TCP handshake | TCP, then an HTTP Upgrade | TCP, then a TLS 1.3 handshake | TCP, TLS 1.3, then an HTTP Upgrade |
| Round trips to CONNACK | 2 | 3 | 3 | 4 |
| CONNACK after the first SYN | 184 ms | 304 ms | 348 ms | 395 ms |
| Bytes added around each MQTT write | None | 2 from the broker, 6 from the client | 22 per TLS record | Both |
| What a passive observer reads | Everything | Everything | Server name, sizes, timing | Server name, sizes, timing |
Ports 1883 and 8883 are registered with IANA for MQTT and MQTT over TLS (MQTT 3.1.1 section 4.2). WebSocket has no MQTT port of its own: brokers often sit behind the web ports 80 and 443, and test.mosquitto.org uses 8080 and 8081.
The WebSocket overhead counts frames with up to 125 bytes of payload, as every frame here has. The 22 TLS bytes are a 5-byte record header plus the 17 bytes AES-GCM adds; more on that in capture 3.
Capture 1: MQTT over TCP
This is MQTT with nothing around it: a TCP connection to port 1883 and every byte in the clear. The session lasts 20 seconds.
What does an MQTT CONNECT contain?
The client's name for itself, the rules for its session, and the protocol version. CONNECT must be the first packet on a new connection (3.1). Here it is 36 bytes:
frame : Frame 4: Packet, 102 bytes on wire (816 bits), 102 bytes captured (816 bits) on interface en0, id 0
Interface id : 0 (en0)
eth : Ethernet II, Src: c8:e0:eb:13:de:6d, Dst: 48:5d:36:c9:c9:6b
Destination : 48:5d:36:c9:c9:6b
Source : c8:e0:eb:13:de:6d
ip : Internet Protocol Version 4, Src: 192.168.1.151, Dst: 5.196.95.208
Differentiated Services Field : 0x00 (DSCP: CS0, ECN: Not-ECT)
010. .... = Flags : 0x2, Don't fragment
tcp : Transmission Control Protocol, Src Port: 50843, Dst Port: 1883, Seq: 1, Ack: 1, Len: 36
Conversation completeness : Complete, WITH_DATA (31)
Flags : 0x018 (PSH, ACK)
Options : (12 bytes), No-Operation (NOP), No-Operation (NOP), Timestamps
TCP Option - No-Operation (NOP)
TCP Option - No-Operation (NOP)
TCP Option - Timestamps : TSval 71086860, TSecr 260134833
Timestamps
SEQ/ACK analysis
mqtt : MQ Telemetry Transport Protocol, Connect Command
Header Flags : 0x10, Message Type: Connect Command
Connect Flags : 0x02, QoS Level: At most once delivery (Fire and Forget), Clean Session Flag
Frame 4, the CONNECT. Under MQ Telemetry Transport Protocol: Protocol Name MQTT, Version 4 (MQTT 3.1.1), Connect Flags 0x02 (Clean Session only), Keep Alive 60, and the Client ID.
Version4 means MQTT 3.1.1. MQTT 5 uses 5.Connect Flags0x02sets only Clean Session: the broker should forget anything left over from an earlier connection with this client ID (3.1.2.4). No username, password, or Will message is sent. (A Will is a message the broker publishes for the client if the client vanishes without a DISCONNECT.)Keep Alive60 means the client promises to send something at least every 60 seconds. If the broker hears nothing for one and a half times that, 90 seconds, it drops the connection (3.1.2.10).Client IDmqtt-explorer-5bd1fce3identifies the session to the broker.
The broker answers in frame 6 with CONNACK, return code 0, Connection Accepted. Its Session Present flag is 0, which section 3.2.2.2 requires after a clean-session CONNECT: there is no earlier session to resume. Two round trips (184 ms) after the first SYN, the client can subscribe.
Why does the client subscribe to both # and $SYS/#?
Because # does not match topics that start with $. A filter that begins with a wildcard never matches a topic name beginning with $ (4.7.2). Brokers publish their own statistics under $SYS/, so a client that wants everything must ask for $SYS/# separately.
Frame 8 carries both requests: two separate SUBSCRIBE packets in one TCP segment, each with its own Packet ID. Each SUBSCRIBE starts with the byte 0x82: packet type 8 plus flag bits 0010, which section 3.8.1 requires.
The broker answers each one in its own SUBACK, matched by Packet ID:
| Packet ID | Filter | SUBACK return code |
|---|---|---|
| 52247 | # | 0x80, Failure (frame 10) |
| 52248 | $SYS/# | 0x00, granted QoS 0 (frame 12) |
0x80 means the broker refused the subscription (3.9.3). MQTT 3.1.1 has no field to say why. The WebSocket capture, about six minutes later, gets the same refusal, so this broker's configuration did not allow a catch-all subscription. The $SYS/# subscription succeeds, and everything that follows comes from it.
What is a retained message?
A message the broker keeps for a topic, so a new subscriber gets the last value at once. Within a millisecond of the SUBACK, frames 13 to 31 deliver 53 retained $SYS statistics: the broker's version (mosquitto version 2.0-dev0), its uptime, its client counts, and its message rates. The broker had about 2,000 clients connected at that moment.
Every one of these PUBLISH packets has its RETAIN flag set. Section 3.3.1.3 sets the flag to 1 when the broker sends a message because of a new subscription, and to 0 when it forwards a message to an existing subscription. So the flag tells the subscriber whether it is seeing a stored value or a live one. Frame 33, 3.2 seconds later, shows the difference: a fresh uptime with RETAIN 0.
Frame 33 also shows what "last value" means. The retained uptime in frame 18 read 272,701 seconds; the live one reads 272,712, eleven seconds more, although only three seconds have passed. The retained copy was the last uptime the broker published, eight seconds before the client subscribed. A retained message is the last value stored, not a current reading.
Why do several PUBLISH packets share one TCP segment?
Because TCP carries a stream of bytes, not messages. The broker writes PUBLISH packets as fast as it can, and TCP packs them into segments as they fit. Frame 30 is one 1,448-byte segment holding 30 complete PUBLISH packets. Frame 17 holds two. A receiver finds the packet boundaries from each fixed header's remaining length, never from the segments.
This matters in Wireshark: the frame count understates the message count. The diagram draws one arrow per MQTT packet, so frame 30 appears as 30 arrows.
What happens to a message published to a $SYS topic?
Nothing visible: the broker does not deliver it. In frames 45, 49, and 67 the client publishes three test messages to $SYS/broker/messages, one JSON, one XML, and one plain text. The client is subscribed to $SYS/#, so it would receive its own messages if the broker forwarded them, and none come back. Section 4.7.2 reserves $ topics for the broker's own use.
The three payloads also show that MQTT does not care what a payload contains. MQTT 3.1.1 has no content-type field (MQTT 5 adds one); the publisher and subscribers must agree on the format themselves. All three are QoS 0, so they carry no Packet ID and get no acknowledgment.
How does an MQTT client disconnect?
It sends DISCONNECT and closes the TCP connection. Frame 69 is the two-byte packet 0xE0 0x00. A DISCONNECT tells the broker to discard the client's Will message, so a clean exit never triggers it (3.14.4). After sending DISCONNECT, the client must close the network connection, and its FIN follows 0.2 ms later.
The session never needed a keepalive: it lasted 20 seconds, well inside the 60-second Keep Alive, so no PINGREQ appears.
Capture 2: MQTT over WebSocket
A web page cannot open a raw TCP connection, but it can open a WebSocket: a two-way byte channel that starts life as an HTTP request. MQTT over WebSocket is how browser dashboards and web apps talk to a broker. The MQTT inside is unchanged; the broker listens on a web port, here 8080.
How does the WebSocket upgrade work?
The client sends an ordinary HTTP/1.1 GET and asks the server to switch protocols (RFC 6455 section 4.1). Frame 4 carries the request headers:
Upgrade: websocketandConnection: Upgradeask for the switch.Sec-WebSocket-Keyis a random value the server must transform and send back.Sec-WebSocket-Protocol: mqttnames the protocol that will run inside. MQTT 3.1.1 section 6 requires a client to offermqttand a server to select it.Sec-WebSocket-Extensions: permessage-deflateoffers compression.
The broker answers in frame 6 with 101 Switching Protocols (section 4.2.2). Its Sec-WebSocket-Accept is the base64 SHA-1 hash of the client's key joined to a fixed GUID; that value proves the server understood the WebSocket request. It selects mqtt and returns no extensions header, so compression is off and the MQTT bytes stay readable. From frame 7 on, the TCP stream carries WebSocket frames instead of HTTP.
The upgrade costs one extra round trip. CONNACK arrives 304 ms after the first SYN, against 184 ms over plain TCP.
Why does the client mask its WebSocket frames?
Because RFC 6455 says it must: a client masks every frame it sends, and a server never masks (section 5.1). The client picks a random 4-byte key for each frame and XORs the payload with it. The point is not secrecy, since the key travels in the frame. Masking stops a malicious page from making the browser send bytes that a proxy in the path would misread as an HTTP request and cache (section 10.3).
Masking makes the two directions different sizes. Each client frame here has a 6-byte header: 2 bytes of framing plus the 4-byte key. Each broker frame has 2. Wireshark removes the mask, so you read the real payload either way.
Why is the CONNECT split across two WebSocket frames?
Because the client wrote it in two pieces, and nothing requires MQTT packets to line up with WebSocket frames. Frame 8 is a WebSocket frame holding a single byte, 0x10, the CONNECT fixed header. Frame 9 holds the other 35 bytes. The client, the mqtt.js library inside MQTT Explorer, sends each packet's first byte as its own write, and each write becomes its own WebSocket frame. Its SUBSCRIBE, PUBLISH, and DISCONNECT packets split the same way.
MQTT 3.1.1 section 6 allows this explicitly: a single WebSocket frame can contain multiple or partial MQTT packets, and a receiver must not assume they are aligned. The broker goes the other way and sends each PUBLISH in a frame of its own. Frame 15 shows both cases at once: the end of one SUBSCRIBE and the whole next one, in one frame.
How do you decode MQTT over WebSocket in Wireshark?
Out of the box, you can't: Wireshark 4.6 shows these frames as WebSocket Binary with an opaque payload, and an mqtt display filter finds nothing. WebSocket hands its payload to another dissector only for subprotocols it has registered, and MQTT is not one of them. The WebSocket dissector tables don't support Decode As either, so no -d option helps.
A short Lua script fixes both problems. It registers the MQTT dissector for the mqtt subprotocol, and it joins MQTT packets that span WebSocket frames, like the split CONNECT above:
-- mqtt_over_ws.lua: decode MQTT carried in WebSocket frames (Wireshark 4.x).
local mqtt = Dissector.get("mqtt")
local tcp_stream = Field.new("tcp.stream")
local proto = Proto("mqttws", "MQTT over WebSocket")
local f_fragment = ProtoField.uint32("mqttws.fragment_len", "MQTT fragment length")
proto.fields = { f_fragment }
local pending = {} -- unparsed bytes per TCP stream and direction
local per_payload = {} -- complete MQTT packets found in each WebSocket payload
-- Length of the MQTT packet at the start of buf, or nil if not known yet.
local function packet_len(buf)
local value, mult, i = 0, 1, 1
while true do
if i >= buf:len() then return nil end
local b = buf:get_index(i)
value = value + (b % 128) * mult
mult = mult * 128
i = i + 1
if b < 128 then break end
if i > 4 then return nil end
end
return i + value
end
function proto.dissector(tvb, pinfo, tree)
local id = pinfo.number .. ":" .. tvb:offset() .. ":" .. tvb:bytes():tohex()
if not pinfo.visited then
local key = tostring(tcp_stream().value) .. ":" .. tostring(pinfo.src) .. ":" .. tostring(pinfo.src_port)
local buf = pending[key] or ByteArray.new()
buf:append(tvb:bytes())
local out = {}
while buf:len() >= 2 do
local total = packet_len(buf)
if total == nil or total > buf:len() then break end
out[#out + 1] = buf:subset(0, total)
if total == buf:len() then
buf = ByteArray.new()
else
buf = buf:subset(total, buf:len() - total)
end
end
pending[key] = buf
per_payload[id] = out
end
local out = per_payload[id] or {}
if #out == 0 then
local sub = tree:add(proto, tvb(), "MQTT fragment, completed in a later WebSocket frame")
sub:add(f_fragment, tvb:len())
pinfo.cols.info:append(" [MQTT fragment]")
return tvb:len()
end
for _, ba in ipairs(out) do
mqtt:call(ba:tvb("Reassembled MQTT"), pinfo, tree)
end
return tvb:len()
end
DissectorTable.get("ws.protocol"):add("mqtt", proto)
Run it with tshark as tshark -2 -X lua_script:mqtt_over_ws.lua -r capture.pcapng -Y mqtt; the -2 gives the script a first pass to join the pieces. In Wireshark, copy the file into the Personal Lua Plugins folder shown under Help → About Wireshark → Folders and restart. The script only works when the capture includes the HTTP Upgrade, because that is where Wireshark learns the subprotocol.
How does a WebSocket connection close?
In two layers, after MQTT finishes. The client sends its DISCONNECT, split into two 1-byte frames (105 and 106). Then, in frame 107, it closes the WebSocket with a Close frame (opcode 8) whose body is empty, so it carries no status code. The broker echoes a Close of its own in frame 111, as RFC 6455 requires, and only then does TCP close. Over plain TCP, the WebSocket layer and its two Close frames don't exist.
Capture 3: MQTT over TLS, without the keys
Port 8883 is MQTT inside TLS, the same encryption HTTPS uses. The client and broker negotiate TLS 1.3 with the cipher suite TLS_AES_256_GCM_SHA384. No key log was recorded, so this capture shows exactly what anyone on the path would see: someone on the same wireless network, an ISP, or a corporate firewall. The diagram's labels are therefore TLS records, not MQTT packets, and every statement here about what is inside a record is an inference from its size and timing.
What can you still see in an encrypted MQTT session?
More than you might expect. The ClientHello in frame 4 travels in the clear:
frame : Frame 4: Packet, 323 bytes on wire (2584 bits), 323 bytes captured (2584 bits) on interface en0, id 0
Interface id : 0 (en0)
eth : Ethernet II, Src: c8:e0:eb:13:de:6d, Dst: 48:5d:36:c9:c9:6b
Destination : 48:5d:36:c9:c9:6b
Source : c8:e0:eb:13:de:6d
ip : Internet Protocol Version 4, Src: 192.168.1.151, Dst: 5.196.95.208
Differentiated Services Field : 0x00 (DSCP: CS0, ECN: Not-ECT)
010. .... = Flags : 0x2, Don't fragment
tcp : Transmission Control Protocol, Src Port: 50858, Dst Port: 8883, Seq: 1, Ack: 1, Len: 257
Conversation completeness : Complete, WITH_DATA (63)
Flags : 0x018 (PSH, ACK)
Options : (12 bytes), No-Operation (NOP), No-Operation (NOP), Timestamps
TCP Option - No-Operation (NOP)
TCP Option - No-Operation (NOP)
TCP Option - Timestamps : TSval 71324757, TSecr 260373808
Timestamps
SEQ/ACK analysis
tls : Transport Layer Security
TLSv1.3 Record Layer : Handshake Protocol: Client Hello
Handshake Protocol : Client Hello
Version : TLS 1.2 (0x0303)
Expert Info (Chat/Deprecated) : This legacy_version field MUST be ignored. The supported_versions extension is present and MUST be used instead.
Cipher Suites (18 suites)
Compression Methods (1 method)
Extension : server_name (len=23) name=test.mosquitto.org
Server Name Indication extension
Extension : extended_master_secret (len=0)
Extension : renegotiation_info (len=1)
Renegotiation Info extension
Extension : supported_groups (len=8)
Supported Groups (3 groups)
Extension : ec_point_formats (len=2)
Elliptic curves point formats (1)
Extension : session_ticket (len=0)
Extension : signature_algorithms (len=20)
Signature Hash Algorithms (9 algorithms)
Signature Algorithm : ecdsa_secp256r1_sha256 (0x0403)
Signature Algorithm : rsa_pss_rsae_sha256 (0x0804)
Signature Algorithm : rsa_pkcs1_sha256 (0x0401)
Signature Algorithm : ecdsa_secp384r1_sha384 (0x0503)
Signature Algorithm : rsa_pss_rsae_sha384 (0x0805)
Signature Algorithm : rsa_pkcs1_sha384 (0x0501)
Signature Algorithm : rsa_pss_rsae_sha512 (0x0806)
Signature Algorithm : rsa_pkcs1_sha512 (0x0601)
Signature Algorithm : rsa_pkcs1_sha1 (0x0201)
Extension : key_share (len=38) x25519
Key Share extension
Key Share Entry : Group: x25519, Key Exchange length: 32
Extension : psk_key_exchange_modes (len=2)
Extension : supported_versions (len=5) TLS 1.3, TLS 1.2
Frame 4, the TLS ClientHello. Under the Handshake Protocol: the 18 offered cipher suites and the extensions, including server_name test.mosquitto.org, supported_versions TLS 1.3 and 1.2, and a key_share for x25519. There is no ALPN extension.
From this one packet and the timing that follows, an observer learns:
- The server name. The Server Name Indication (SNI) extension says
test.mosquitto.orgin the clear. - The TLS settings. The client offers TLS 1.3 and 1.2 and 18 cipher suites; the ServerHello in frame 6 picks TLS 1.3,
0x1302, and an x25519 key exchange. - Not the protocol name. There is no ALPN extension, so nothing in the handshake says MQTT. Port 8883 gives it away anyway.
- Every record's size and time. These turn out to reveal a great deal, as the next section shows.
What the observer cannot see: the broker's certificate, any topic, any payload, the client ID, or any MQTT return code. In TLS 1.3, every handshake message after the ServerHello is encrypted (RFC 8446 section 2), including the Certificate. In TLS 1.2 the certificate would travel in the clear. Wireshark labels every encrypted record Application Data, because the outer content type is always 23; the real type is hidden inside the encryption (section 5.2).
How do record sizes give away MQTT packets?
With AES-GCM, every TLS 1.3 record is exactly 17 bytes longer than its content: 1 byte for the hidden content type and a 16-byte authentication tag (section 5.2). Subtract 17, and you have the size of what is inside.
This client makes the arithmetic easy. It writes each field of each MQTT packet as a separate TLS record. Frame 9 carries the client's Finished and then nine tiny records. Compare their contents, by size, with the CONNECT from capture 1:
| Record length | Content (length - 17) | CONNECT field of the same size |
|---|---|---|
| 18 | 1 byte | Fixed header, 0x10 |
| 18 | 1 byte | Remaining length, 34 |
| 19 | 2 bytes | Protocol-name length |
| 21 | 4 bytes | MQTT |
| 18 | 1 byte | Protocol level, 4 |
| 18 | 1 byte | Connect flags |
| 19 | 2 bytes | Keep Alive |
| 19 | 2 bytes | Client-ID length |
| 39 | 22 bytes | Client ID: mqtt-explorer-5bd1fce3 is 22 characters |
The nine records hold 36 bytes, exactly the size of the plain CONNECT. The rest of the session reads the same way:
- The CONNACK is the 4-byte record in frame 14.
- The two SUBSCRIBE packets are twelve records in frame 17. One of them is 6 bytes, the length of
$SYS/#. - The SUBACKs are the two 5-byte records in frames 19 and 21. Their return codes are hidden.
- The retained burst is one record per PUBLISH. All 20 records in frame 24 match, size for size and in order, the PUBLISH packets of the retained burst in capture 1.
- The client's test messages are five records each (frames 34 and 38), one of them 20 bytes: the length of
$SYS/broker/messages. - The close is two 1-byte records (frame 70), the size of
0xE0 0x00, then a 2-byte record, the size of a TLSclose_notifyalert.
So TLS hid every value, but leaked the shape: how many messages, how big, and when. For a smart-home device that publishes "door open" and "door closed" as different-size payloads, size alone could tell an observer which one it sent. TLS 1.3 lets a sender pad records to hide their size (section 5.4), and a client that writes each packet as a single record leaks less, but neither happened here.
The TLS handshake costs the same one extra round trip as the WebSocket upgrade, and the client saves another by sending its CONNECT in the same segment as its Finished, without waiting for the broker. CONNACK arrives 348 ms after the first SYN.
What about MQTT over TLS and WebSocket together?
The fourth capture, mqtt_tls_ws.pcapng, runs WebSocket inside TLS on port 8081, the setup a browser uses for a wss:// broker URL. It is not drawn as a separate diagram because it looks like capture 3 from outside. Its record sizes match capture 2 instead: the first client records hold 264 bytes (the HTTP GET in capture 2 is 264 bytes), 159 bytes back (the 101 response), then 7 and 41 bytes (the split CONNECT, with its 6-byte WebSocket headers). Here each WebSocket frame travels as one TLS record. It is the slowest of the four to connect, at four round trips and 395 ms to CONNACK.
How can you decrypt your own MQTT over TLS?
Give Wireshark the session keys. Most TLS libraries can write them to a key log file: browsers do when the SSLKEYLOGFILE environment variable is set, and Node.js does with its --tls-keylog option. Load the file under Wireshark's TLS protocol preferences, "(Pre)-Master-Secret log filename", and the records decode to MQTT, as in our decrypted QUIC and HTTP/3 walkthrough. Without the keys, capture 3 is what you get.
Capture 4: CoAP over UDP
CoAP, the Constrained Application Protocol, brings the web's request-and-response model to devices too small for HTTP. A client sends GET, POST, PUT, or DELETE to a URI, and the server answers with a response code, much like HTTP. But CoAP runs over UDP, with a 4-byte binary header and no connection, on port 5683 (RFC 7252 section 6.1). In this capture, a client walks through the resources of a public CoAP test server at 52.45.123.182.
How is CoAP different from MQTT?
| MQTT | CoAP | |
|---|---|---|
| Model | Publish and subscribe through a broker | Request and response, client to server |
| Transport | TCP (also inside WebSocket or TLS) | UDP (DTLS for security) |
| Default ports | 1883, and 8883 with TLS | 5683, and 5684 with DTLS |
| Connection | A long-lived session, opened with CONNECT | None: the first packet is the request |
| Reliability | TCP, plus QoS 0, 1, or 2 | Confirmable messages retransmitted until acknowledged |
| Smallest header | 2 bytes | 4 bytes |
| Updates pushed to clients | Built in, through subscriptions | With the Observe option (RFC 7641) |
MQTT suits many devices reporting to one hub or cloud service. CoAP suits devices that sleep most of the time, run on very constrained networks, or are easier to model as resources with URIs.
How does CoAP make UDP reliable?
With message types and Message IDs (section 4). A Confirmable (CON) message must be acknowledged; the sender retransmits it, waiting 2 to 3 seconds at first and doubling each time, up to 4 times (section 4.8). A Non-confirmable (NON) message is sent once. Every request in this capture is Confirmable.
Two numbers keep the exchanges straight:
- The Message ID pairs a message with its acknowledgment (ACK) and lets the receiver spot duplicates.
- The Token, chosen by the client, pairs a response with its request (section 5.3.2). Here every token is 2 bytes.
Most of the time these two pairings coincide, because the response rides inside the ACK.
What is a CoAP piggybacked response?
A response carried in the ACK itself, the fast path (section 5.2.1). In frame 1 the client sends GET /advanced as a Confirmable message with Message ID 1697 and Token 7153. Frame 2, 18 ms later, is an ACK with the same Message ID and Token and code 2.05 Content, carrying the 17-byte body. One message acknowledges the request and answers it.
CoAP writes response codes as class.detail: 2.05 Content is the equivalent of HTTP's 200 OK, and 4.04 Not Found is HTTP's 404. Most requests in the capture get piggybacked responses, in 10 to 45 ms.
What is a CoAP separate response?
A response sent later, as a new message, when the server cannot answer at once (section 5.2.2). The server first sends an empty ACK, which stops the client's retransmissions, and sends the real response when it is ready. The resource /advancedSeparate is built to show it:
The empty ACK in frame 4 echoes the request's Message ID, 4727, but has no Token: an empty message (code 0.00) must not carry one (section 4.1). The response in frame 5 is a new Confirmable exchange started by the server, with the server's own Message ID, 103, so only the Token, 6562, ties it to the request. Because it is Confirmable, the client acknowledges it in frame 6.
The capture has three separate responses. The server's Message IDs count up, 103, 104, and 105:
| Request | Empty ACK after | Response after | Server Message ID |
|---|---|---|---|
/advancedSeparate (frame 3) | 12.5 ms | 5.1 s | 103 |
/long (frame 19) | 2.1 s | 10.1 s | 104 |
/separate (frame 23) | 16 ms | 5.1 s | 105 |
For /long, the server took 2.1 seconds to send even the empty ACK. The client's first retransmission timer runs for 2 to 3 seconds, and no retransmission appears, so the ACK arrived in time.
The client's own ACKs (frames 6, 22, and 26) have a quirk: each one is an empty message that still echoes the Token. Section 4.1 says an empty message must have a Token length of 0 and treats anything more as a message format error. A server that rejected these ACKs would ignore them and retransmit its response (section 4.2). This server accepted them, and no retransmission followed.
How does CoAP send a large resource?
In blocks, using the Block2 option (RFC 7959). In frame 10, the response to GET /big carries Block2 with block number 0, the More flag set, and a block size of 1,024 bytes. The client asks for block 1 in frame 11, with a new Message ID but the same Token. Frame 12 delivers it with More clear, and Wireshark joins the two into 2,041 bytes. Each block is its own Confirmable exchange, so a lost block costs one retransmission, not the whole transfer.
What do CoAP POST and DELETE look like?
The sixth capture, coap_post_delete.pcapng, works on the server's /storage resource. It is short enough to read as a table:
| Frame | Request | Response |
|---|---|---|
| 1, 2 | GET /storage | 2.05 Content: Storage Resource for PUT, POST and DELETE |
| 3, 4 | POST /storage, an 80-byte XML document | 2.01 Created, with a Location-Path option, storage |
| 5, 6 | GET /storage | 2.05 Content: the 80-byte XML document |
| 7, 8 | DELETE /storage | 2.02 Deleted |
| 9, 10 | GET /storage | 4.04 Not Found |
| 11, 12 | POST /storage again | 4.05 Method Not Allowed |
Every response is piggybacked. The DELETE in frame 7 is the one request that carries no Token, which CoAP allows (section 5.3.1). After the DELETE, the resource is gone, and this server refuses a second POST to it.
Frequently asked questions
What port does MQTT use? 1883 for unencrypted MQTT and 8883 for MQTT over TLS, both registered with IANA. MQTT over WebSocket has no fixed port; it usually shares a web server's ports 80 and 443.
Is MQTT encrypted? Not by itself. Over port 1883, everything travels in the clear, as capture 1 shows, including any username and password in the CONNECT. Use TLS on port 8883, or WebSocket over TLS.
Why can't I see MQTT in Wireshark? Either the traffic is encrypted, so it shows as TLS Application Data, or it is inside WebSocket, which Wireshark doesn't decode as MQTT by default. For WebSocket, use the Lua script in capture 2; for TLS, you need the session keys.
What does a SUBACK return code of 0x80 mean? The broker refused that subscription. MQTT 3.1.1 gives no reason; MQTT 5 adds reason codes. In capture 1, test.mosquitto.org refuses # and accepts $SYS/#.
What is the RETAIN flag? When a client publishes with RETAIN set, the broker stores the message as the topic's last value. When the broker delivers a stored message to a new subscriber, it sets RETAIN to 1; when it forwards a live message, RETAIN is 0.
Does # match $SYS topics? No. A filter that starts with a wildcard never matches topic names that start with $. Subscribe to $SYS/# explicitly.
MQTT or CoAP? MQTT when many devices report to a central broker over TCP. CoAP when devices are very constrained or sleep most of the time, or when a resource-and-URI model fits better, over UDP.
Takeaways
- MQTT is small on the wire. A DISCONNECT is 2 bytes, a CONNECT 36, and one TCP segment can carry 30 PUBLISH packets.
#doesn't cover$SYS. Clients that want broker statistics must subscribe to$SYS/#too, and a broker can refuse any subscription with0x80.- RETAIN tells stored from live. The broker sets it on messages sent because of a new subscription and clears it on normal forwarding, and a retained value can be stale.
- Each transport costs about one round trip. CONNACK came after 2 round trips over TCP, 3 over WebSocket or TLS, and 4 over both.
- MQTT packets need not line up with anything. Not with TCP segments, not with WebSocket frames, not with TLS records.
- TLS hides values, not shape. Without keys, the server name, record sizes, and timing still outline the whole session.
- CoAP gets reliability from Confirmable messages. The Message ID pairs a message with its ACK, and the Token pairs a response with its request, which is what makes separate responses work.