Module 7: Real-time Applications

Learn to build real-time applications with WebSockets, Socket.io, and live data streaming using Node.js.

Back to Course|4.5 hours|Advanced

Real-time Applications

Learn to build real-time applications with WebSockets, Socket.io, and live data streaming using Node.js.

Progress: 0/4 topics completed0%

Select Topics Overview

WebSocket Implementation

Learn to implement WebSockets for real-time bidirectional communication

Content by: Bansi Patel

Node.js Developer

Connect

What are WebSockets?

WebSockets provide a persistent connection between a client and server, allowing real-time bidirectional communication. Unlike HTTP requests, WebSockets maintain an open connection for instant data exchange.

Basic WebSocket Server

Code Example
// Install ws library
npm install ws

// Basic WebSocket server
const WebSocket = require('ws');

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

wss.on('connection', function connection(ws) {
    console.log('New client connected');

    // Send welcome message
    ws.send(JSON.stringify({
        type: 'welcome',
        message: 'Welcome to the WebSocket server!'
    }));

    // Handle incoming messages
    ws.on('message', function incoming(message) {
        try {
            const data = JSON.parse(message);
            console.log('Received:', data);

            // Echo the message back
            ws.send(JSON.stringify({
                type: 'echo',
                message: data.message,
                timestamp: new Date().toISOString()
            }));
        } catch (error) {
            ws.send(JSON.stringify({
                type: 'error',
                message: 'Invalid JSON format'
            }));
        }
    });

    // Handle client disconnect
    ws.on('close', function close() {
        console.log('Client disconnected');
    });

    // Handle errors
    ws.on('error', function error(err) {
        console.error('WebSocket error:', err);
    });
});

console.log('WebSocket server running on port 8080');
Swipe to see more code

WebSocket Client Implementation

Code Example
// WebSocket client (browser)
const ws = new WebSocket('ws://localhost:8080');

ws.onopen = function(event) {
    console.log('Connected to WebSocket server');
    
    // Send a message
    ws.send(JSON.stringify({
        type: 'chat',
        message: 'Hello from client!'
    }));
};

ws.onmessage = function(event) {
    const data = JSON.parse(event.data);
    console.log('Received:', data);
    
    if (data.type === 'welcome') {
        console.log('Server says:', data.message);
    } else if (data.type === 'echo') {
        console.log('Echo:', data.message);
    }
};

ws.onclose = function(event) {
    console.log('Disconnected from server');
};

ws.onerror = function(error) {
    console.error('WebSocket error:', error);
};

// Send message function
function sendMessage(message) {
    if (ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
            type: 'chat',
            message: message
        }));
    }
}
Swipe to see more code

🎯 Practice Exercise

Test your understanding of this topic:

Additional Resources

📚 Recommended Reading

  • WebSocket Protocol Specification
  • Socket.io Documentation
  • Real-time Application Patterns

🌐 Online Resources

  • WebSocket Tutorial
  • Socket.io Getting Started
  • Real-time Chat Applications

Ready for the Next Module?

Continue your learning journey and master the next set of concepts.

Continue to Module 8