HTML and CSS Reference
TCP only communicates byte streams, so message boundaries must be represented
in a higher-level protocol. One very common mistake made by beginning socket
programmers using TCP is assuming that every call to send() will result in one
successful receive . While this may happen to be true for simple tests, when load and
latency vary, the bytes sent on a TCP socket will be unpredictably fragmented. TCP
data can be spread over multiple IP packets or combined into fewer packets at the
discretion of the operating system. The only guarantee in TCP is that the individual
bytes that arrive on the receiving side will arrive in order. Unlike TCP, WebSocket
transmits a sequence of discrete messages. With WebSocket, multi-byte messages will
arrive in whole and in order, just like HTTP. Because message boundaries are built into
the WebSocket Protocol, it is possible to send and receive separate messages and avoid
common fragmentation mistakes.
It bears mentioning that before the Internet, another networking model was being
followed: Open Systems Interconnection (OSI), which includes seven layers: physical,
data link, network, transport, session, presentation, and application. However, while the
terminology may be similar, OSI was not designed with the Internet in mind. The TCP/IP
model, which was designed for the Internet, comprises just four layers: link, Internet,
transport, and application, and is the model that drives the Internet today.
IP is at the Internet layer and TCP layers on top of IP at the transport layer.
WebSocket layers on top of TCP (and therefore IP), and is also considered a transport
layer because you can layer application-level protocols on top of WebSocket.
Inspecting WebSocket Traffic
In Chapter 2, we used the WebSocket API without really seeing what was happening at
the network level. If you want to see WebSocket traffic flowing over a network,
you can use tools like Wireshark ( http://www.wireshark.org/ ) or tcpdump
( http://www.tcpdump.org/ ) and inspect what's inside the communication stack.
Wireshark enables you to “dissect” the WebSocket protocol, which lets you view the parts of
the WebSocket Protocol we'll discuss later in this chapter (for example, opcodes, flags, and
payloads) in a convenient UI, as shown in Figure 3-4 . It will even display unmasked versions
of messages sent from WebSocket clients. We'll discuss masking later in this chapter.
Appendix A covers WebSocket traffic debugging tools in detail.