CodeBlanks Logo Icon CodeBlanks

Summary - WebSocket

Combine server, message and broadcast to write a chat server.

Summary - WebSocket

In this group you learned the WebSocket foundation: the ws module, WebSocketServer, the connection event, the message event, and broadcast. WebSocket provides real-time bidirectional communication.

HTTP is request-response; WebSocket keeps the connection open. It is ideal for chat, notifications, and games. The ws module is lightweight; for more features use Socket.io. The core pattern: connection → message → broadcast.

When to use WebSocket

WebSocket is used when you need real-time data flow: chat, live notifications, task status, games. It is ideal whenever the server must push data instantly.

But for one-off request-response, WebSocket is overkill; HTTP is enough. WebSocket carries the cost of keeping connections open; so it pays off when the persistent-connection advantage is real. For semi-real-time, SSE (Server-Sent Events) is an alternative; but if you need bidirectional, WebSocket is required.

Practice Log the type of WebSocketServer

Import the WebSocketServer class from ws. Log typeof WebSocketServer.

Starter code

index.js
// import the module, get the server class

// log its type

Sample solution

index.js
const { WebSocketServer } = require("ws");
console.log(typeof WebSocketServer);

Expected output

function

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the main advantage of WebSocket over HTTP?

  • Faster file reads
  • A persistent two-way connection Correct answer
  • Daha az bellek
  • Shorter code

Explanation: WebSocket provides a bidirectional persistent connection.

2 Match each piece to its role

Term Meaning
ws WebSocket module
WebSocketServer Server class
connection On client connect
broadcast Send to all

All lessons in Advanced