0
0
Node.jsframework~5 mins

WebSocket protocol concept in Node.js

Choose your learning style9 modes available
Introduction

WebSocket lets your app talk to a server in real-time. It keeps the connection open so messages can flow back and forth instantly.

You want a chat app where messages appear instantly.
You need live updates like sports scores or stock prices.
You build a multiplayer game that needs fast communication.
You want to show notifications without refreshing the page.
Syntax
Node.js
const ws = new WebSocket('ws://example.com/socket');

ws.onopen = () => {
  ws.send('Hello Server!');
};

ws.onmessage = (event) => {
  console.log('Message from server:', event.data);
};

ws.onclose = () => {
  console.log('Connection closed');
};

Use ws:// for unencrypted and wss:// for secure connections.

Events like onopen, onmessage, and onclose handle connection states.

Examples
Connect securely using wss:// and send a message when connected.
Node.js
const ws = new WebSocket('wss://example.com/socket');

ws.onopen = () => {
  ws.send('Hi!');
};
Listen for messages from the server and log them.
Node.js
ws.onmessage = (event) => {
  console.log(`Received: ${event.data}`);
};
Detect when the connection closes and log it.
Node.js
ws.onclose = () => {
  console.log('Socket closed');
};
Sample Program

This Node.js program creates a WebSocket server on port 8080. When a client connects, it logs a message. It listens for messages from the client, logs them, and sends back the same message prefixed with 'Echo:'. It also logs when the client disconnects.

Node.js
import WebSocket from 'ws';

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

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

  socket.on('message', (message) => {
    console.log('Received:', message.toString());
    socket.send(`Echo: ${message}`);
  });

  socket.on('close', () => {
    console.log('Client disconnected');
  });
});

console.log('WebSocket server running on ws://localhost:8080');
OutputSuccess
Important Notes

WebSocket keeps the connection open, unlike HTTP which closes after each request.

Use secure WebSocket (wss://) for sensitive data to protect privacy.

WebSocket works well for apps needing instant updates without refreshing.

Summary

WebSocket creates a live, two-way connection between client and server.

It is great for real-time apps like chat, games, and live feeds.

Use event handlers to send and receive messages easily.