Node.js Course
Node.js
/
Intermediate

WebSockets

Definition

A computer communications protocol providing full-duplex communication channels over a single, long-lived TCP connection.

Explain Like I'm New

Standard HTTP is like sending a letter. You ask for the homepage, the server sends it, and the connection is closed. If someone sends you a chat message, the server can't reach you because the connection is dead. WebSockets are a phone call. You call the server, and NEITHER of you hangs up. The line stays open permanently. If someone chats you, the server instantly speaks into the open phone line: 'Hey, new message!'.

Real World Example

Multiplayer browser games, Live stock market tickers, and Chat applications (Discord/Slack). All require instantaneous, two-way communication without the browser constantly refreshing.

Common Use Cases

  • •Real-time applications
  • •Collaborative editing (Google Docs)

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Are WebSockets unidirectional or bidirectional?

intermediate

  • Does the client have to constantly 'ask' the server if there is new data in a WebSocket?

Flash Cards

Question

Unidirectional or bidirectional?

Click to reveal answer
Answer

Bidirectional (Full-duplex). Both the client and the server can send messages to each other at the exact same time.

Question

Does the client have to ask?

Click to reveal answer
Answer

No. Unlike HTTP 'Long Polling', the client just sits quietly. The server PUSHES the data down the open connection the millisecond it becomes available.