Node.js Real-Time with WebSockets

In this tutorial, we'll learn how to build real-time web applications using WebSockets in Node.js. WebSockets provide full-duplex communication channels over a single TCP connection.

1. Setting Up WebSocket Server with `ws`

We will start by installing the WebSocket library and setting up a basic server that listens for incoming WebSocket connections.

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

wss.on('connection', (ws) => {
    ws.on('message', (message) => {
        console.log(`Received: ${message}`);
    });

    ws.send('Hello! You are connected');
});

This basic WebSocket server listens on port 8080 and sends a welcome message to each new client.

2. Handling Real-Time Communication

Now, we can handle real-time messages sent by the client and broadcast to all connected clients.

wss.on('connection', (ws) => {
    ws.on('message', (message) => {
        wss.clients.forEach((client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });
});

This code listens for messages from clients and broadcasts them to all other connected clients.

3. Real-Time Client-Side Integration

Next, we will write the client-side code to connect to the WebSocket server and send/receive messages in real-time.

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

socket.addEventListener('open', () => {
    socket.send('Hello Server!');
});

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

This client-side code connects to the WebSocket server and sends a message once the connection is open. It also listens for messages from the server.

0 Interaction
258 Views
Views
44 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home