WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Node.js · Intermediate · question 34 of 100

Explain the concept of ’WebSockets’ and how to use them in Node.js applications.?

📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

WebSockets is a communication protocol that enables two-way communication between a client and a server over a single, long-lived connection. Unlike the traditional request-response model of HTTP, the WebSocket protocol provides full-duplex communication, allowing messages to be sent simultaneously in both directions. This bidirectional communication greatly reduces the latency and overhead associated with opening and closing multiple connections, making it particularly suitable for real-time applications, such as chat applications, online gaming, and live data feeds.

To use WebSockets in a Node.js application, you first need to install the ‘ws‘ package, which provides a simple WebSocket server and client. To install the package, run the following command:

npm install ws

Once you have the package installed, you can create a simple WebSocket server as follows:

const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (socket) => {
  console.log('Client connected');

  // Listen for messages from the client
  socket.on('message', (message) => {
    console.log(`Received: ${message}`);
    
    // Echo the message back to the client
    socket.send(`You sent: ${message}`);
  });

  // Listen for the socket to close
  socket.on('close', () => {
    console.log('Client disconnected');
  });
});

This example creates a simple WebSocket server that listens for incoming connections on port 8080. When a client connects, it logs a message, and sets up listeners for the ‘’message’‘ and ‘’close’‘ events from the connected client. When the server receives a message from the client, it echoes the message back to the client.

To connect to the WebSocket server from a client-side script, you can use the built-in ‘WebSocket‘ object in most modern web browsers:

const socket = new WebSocket('ws://localhost:8080');

socket.addEventListener('open', () => {
  console.log('Connected to server');
  socket.send('Hello, server!');
});

socket.addEventListener('message', (event) => {
  console.log(`Received: ${event.data}`);
});

socket.addEventListener('close', () => {
  console.log('Disconnected from server');
});

This client-side example connects to the WebSocket server and sends an initial message. It also sets up event listeners to handle messages from the server and the closing of the connection.

In summary, the WebSocket protocol enables two-way communication between a client and a server over a persistent connection, which is well-suited for real-time applications. Node.js applications can use packages like ‘ws‘ to create WebSocket servers and communicate with connected clients.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Node.js interview — then scores it.
📞 Practice Node.js — free 15 min
📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

All 100 Node.js questions · All topics