Open In App

Web-Socket in Node

Last Updated : 15 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

WebSockets in Express.js and Node.js enable real-time, two-way communication between a website and its server. This allows for features like live chat, instant updates, and interactive experiences.

  • WebSockets maintain a persistent connection, unlike typical web requests.
  • Libraries such as ws and socket.io simplify the integration of WebSockets into Node.js and Express.js applications.

Why use WebSockets?

Here are the reasons why WebSockets are a great choice for certain applications:

  • Real-time updates: See changes instantly, like in a live game or chat.
  • Two-way communication: Both the website and the server can send messages at any time.
  • Faster than usual: No waiting for the website to “call” the server every time.

How WebSockets Work in Node.js?

WebSockets provide a persistent, two-way communication channel between a client (like a web browser) and a server (like a Node.js server). This allows for real-time data exchange without the overhead of repeatedly establishing connections, which is how traditional HTTP requests work.

  • Handshake: The client and server initially establish a WebSocket connection through an HTTP handshake. This “upgrades” the connection to a WebSocket.
  • Persistent Connection: Unlike HTTP, the WebSocket connection remains open, allowing for continuous communication.
  • Bidirectional Communication: Both the client and the server can send data to each other at any time.
  • Real-time Data Exchange: Data is pushed instantly, without the need for the client to repeatedly request updates.
  • Event-driven Model: socket.io (a popular WebSocket library) uses an event-driven model to manage communication, making it easy to handle messages and other events.

Approach to Implement Web Sockets

Web sockets can be implemented in the following ways:

1. Server-Side (Node.js):

Here’s the approach and what each step does:

  • Require Modules: Bring in the necessary tools: express (for creating the server), socket.io (for WebSockets), and http (for handling web requests).
  • Create HTTP Server: Set up the basic structure of a web server using express and http. This is where your website files will be served from.
  • WebSocket Connection: Use socket.io to create the “always-on” connection. This is the key part that makes WebSockets work.
  • Handle Connections: When a user visits your website, this code handles that connection. You can send a welcome message, listen for messages from the user, and manage what happens when they leave.

2. Client-Side (HTML/JavaScript):

Here’s what you need on the website itself:

  • HTML Form: Create a simple form with an input field for typing messages and a button to send them.
  • Include Socket.IO: Add the socket.io library to your HTML file. This allows your website to talk to the server using WebSockets. You’ll typically include it with a <script> tag.
  • Establish Connection: When the webpage loads, connect to the WebSocket server.
  • Handle Messages: Set up listeners to receive messages from the server and display them on the page.
  • Send Messages: When the user submits the form, send the message to the server using the WebSocket connection.
  • Handle Disconnections: Manage what happens when the connection between the website and server is lost.

Communication Flow:

  1. Connection: User visits the website, establishing a WebSocket connection.
  2. Welcome: The server sends a “welcome” message to the user.
  3. User Input: The user types a message and clicks “Send.”
  4. Message Sent: The website sends the message to the server via the WebSocket.
  5. Server Receives: The server receives the message.
  6. Broadcast (Optional): The server can then send the message to other connected users (like in a chat app).
  7. Display: The website displays the message.
  8. Disconnection: User leaves the website, closing the WebSocket connection.

Implementing WebSockets in Node.js

Here’s a step-by-step guide to adding WebSockets to your Node.js application:

1. Server-Side (Node.js)

This part handles the WebSocket connection and manages communication between the server and the clients (browsers).

Installation:

First, you need to install the necessary packages. Open your terminal in your project directory and run:

npm install express socket.io

This installs express (for creating the server) and socket.io (for handling WebSockets).

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIO(server); // Initialize socket.io
const port = process.env.PORT || 3000;

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/client.html"); // Serve the HTML file
});

io.on('connection', (socket) => {
    console.log('New user connected');

    socket.emit('newMessage', { from: 'Server', text: 'Welcome!', createdAt: Date.now() });

    socket.on('createMessage', (message) => {
        console.log('New message:', message);
        io.emit('newMessage', message); // Send to everyone
    });

    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});

server.listen(port, () => {
    console.log(`Server is up on port ${port}`);
});
  • Sets up a web server using Express.js and enables WebSocket communication with Socket.io.
  • Handles new user connections, sending a welcome message and listening for incoming messages. These incoming messages are then broadcast to all connected users.
  • Manages user disconnections.

Output

Implementing Web Sockets server-side

2. Setting up the Client (HTML/JavaScript)

This part runs in the user’s web browser and lets them talk to the server. We’re using basic HTML and JavaScript here, but you could also use other tools like React or Angular to build the client-side of your application.

HTML (client.html):

<html>
<head></head>
<body>
    <form id="message-form">
        <input type="text" id="message-input" placeholder="Enter message" autocomplete="off">
        <button type="submit">Send</button>
    </form>
    <ul id="messages"></ul>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io();
        socket.on('connect', () => {
            console.log('Connected to server');
        });
        socket.on('newMessage', (message) => {
            const li = document.createElement('li');
            li.textContent = `${message.from}: ${message.text}`;
            document.getElementById('messages').appendChild(li);
        });
        document.getElementById('message-form').addEventListener('submit', (e) => {
            e.preventDefault();
            const message = document.getElementById('message-input').value;
            socket.emit('createMessage', {
                from: 'User',
                text: message,
                createdAt: Date.now()
            });
            document.getElementById('message-input').value = '';
        });
        socket.on('disconnect', () => {
            console.log('Disconnected from server');
        });
    </script>
</body>
</html>
  • Includes the Socket.io client library to enable WebSocket communication with the server.
  • Establishes a connection with the server and listens for incoming messages, displaying them in the browser.
  • Sends messages to the server when the user submits the form.

Output

Implementing web-sockets clientside

Web-Socket in Node -FAQs

How are WebSockets different from regular HTTP requests?

WebSockets maintain a persistent connection for real-time communication, while HTTP requests are one-time interactions.

What libraries are commonly used for WebSockets in Node.js?

socket.io and ws are the most popular choices, simplifying WebSocket implementation.

Can WebSockets be used for real-time applications?

Yes, they are ideal for applications like chat, live updates, and multiplayer games.

Do WebSockets require a special server?

No, they can be integrated with existing HTTP servers using libraries like socket.io.

Are WebSockets supported by all browsers?

Yes, modern browsers support WebSockets.



Next Article

Similar Reads

three90RightbarBannerImg