WebSockets allow a browser and server to keep one connection open so both sides can send data at any time. This cheat sheet covers how WebSockets work, how they differ from normal HTTP requests, and why they are useful for chat, games, dashboards, and live collaboration. Students need this reference to connect networking ideas with real-time app design and to recognize when persistent communication is the right tool.
The core idea is that a WebSocket starts with an HTTP upgrade request and then switches to a full-duplex connection. After the handshake, the client and server exchange messages instead of repeatedly creating new HTTP requests. Important concepts include connection events, message formats, latency, heartbeats, reconnection, and secure use of wss://.
Key Facts
- A WebSocket connection begins with an HTTP request that includes Upgrade: websocket and then switches protocols if the server accepts it.
- Use ws:// for an unencrypted WebSocket connection and wss:// for an encrypted WebSocket connection over TLS.
- WebSockets are full-duplex, which means the client and server can send messages to each other independently at the same time.
- The main browser events are open, message, error, and close, and each event should be handled in client code.
- A common client pattern is socket = new WebSocket(url), then socket.send(data) after the open event fires.
- Latency is the time delay between sending data and receiving a response, and lower latency is important for real-time apps.
- Heartbeats use ping and pong messages or app-level keepalive messages to detect broken connections.
- Real-time systems should handle reconnects, duplicate messages, invalid data, and server overload instead of assuming the connection always works.
Vocabulary
- WebSocket
- A network protocol that keeps a persistent connection open so a client and server can exchange messages in real time.
- Handshake
- The starting request and response that upgrade an HTTP connection into a WebSocket connection.
- Full-duplex
- A communication style where both sides can send and receive data at the same time.
- Latency
- The delay between when data is sent and when it is received or acted on.
- Heartbeat
- A small repeated message used to confirm that a connection is still alive.
- Message frame
- A structured unit of data sent across a WebSocket connection, such as text, binary data, ping, pong, or close.
Common Mistakes to Avoid
- Sending data before the open event fires, because the WebSocket may not be ready and the message can fail.
- Using WebSockets for simple one-time data requests, because normal HTTP is often simpler and more efficient for request-response tasks.
- Forgetting to validate incoming messages, because clients and servers should never trust data just because it came through an open connection.
- Ignoring the close and error events, because real networks disconnect and the app needs recovery behavior such as retrying or showing status.
- Assuming wss:// is optional for production, because secure sites should use encrypted WebSocket connections to protect data and avoid browser security problems.
Practice Questions
- 1 A live chat app sends 24 messages per minute from one user. If each message is about 500 bytes, about how many bytes does that user send in 5 minutes, not counting headers?
- 2 A game client receives position updates every 50 milliseconds. How many updates does it receive in 1 second?
- 3 Write the basic sequence of steps for opening a WebSocket connection, sending one message, and closing the connection.
- 4 Explain why a stock price dashboard or multiplayer game benefits more from WebSockets than from repeatedly refreshing a webpage.
Understanding WebSockets & Real-Time Communication
A WebSocket is useful because many programs need to react to events, not just answer a single request. In a chat room, a new message should appear for every connected person quickly. In an online game, each player sends movement updates while receiving updates about others.
A stock display, classroom poll, or delivery tracker can receive changing data as it happens. The server usually keeps a list of connected clients.
When one important event occurs, it can send a message to the relevant clients. This is often called broadcasting when many clients receive the same update.
Messages need a clear structure. Programs often send text in JSON format because it can hold named pieces of data such as a message type, a user name, and content. A message type tells the receiving code what action to take.
For example, one message may represent a chat post, while another reports a player position. The receiver must never trust incoming data automatically.
It should check that required fields exist, that values have the expected type, and that a user is allowed to perform the action. Careful validation prevents crashes, bugs, and some security problems.
Network delays are not always steady. A message can arrive late because of weak Wi Fi, mobile data, congestion, or a busy server. Messages can be lost when a device changes networks or sleeps.
A reconnecting client should wait briefly before trying again. If it retries instantly and repeatedly, many clients can overload a server during an outage. This is why programs often increase the wait after each failed attempt.
They may use a random small delay so every client does not reconnect at the exact same moment. A client should restore its state after reconnecting, such as rejoining a room or requesting the latest data.
Real-time does not mean perfect instant delivery. It means the system is designed to reduce delay and react to change quickly. For some tasks, a delay of a few milliseconds matters a great deal.
Fast games and shared drawing tools are examples. For a dashboard that updates every few seconds, simpler methods may be enough. WebSockets can use server memory and network capacity because each active user has a connection.
Servers may need to divide clients across several machines and route messages to the correct machine. When studying this topic, follow the full path of one message from a user action, through validation and server logic, to delivery and display. Then consider what happens if any step is slow, repeated, malformed, or disconnected.