Lesson 49-Koa WebSocket Integration


WebSocket Integration

Installing Required Packages

First, you need to install the koa-websocket and ws packages.

npm install koa-websocket ws

Initializing WebSocket

In the main entry file of your Koa2 application, use koa-websocket to replace the standard Koa instance, then define the WebSocket routes and event handlers.

const Koa = require('koa');
const koaBody = require('koa-body');
const koaWebsocket = require('koa-websocket');
const WebSocket = require('ws');

const app = koaWebsocket(new Koa());

// Middleware
app.use(koaBody());

// WebSocket route
app.ws.use(async (ws, ctx) => {
    // Triggered when a WebSocket connection is established
    ws.on('message', (message) => {
        console.log(`Received: ${message}`);
        // Send a response back to the client
        ws.send(`Echo: ${message}`);
    });

    // Triggered when the WebSocket connection is closed
    ws.on('close', () => {
        console.log('Connection closed');
    });
});

// Start the server
app.listen(3000, () => {
    console.log('Server is listening on port 3000');
});

Client Connection

On the client side, you can use the browser’s built-in WebSocket object to connect to your Koa2 server.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Client</title>
    <script>
        const socket = new WebSocket('ws://localhost:3000');

        socket.addEventListener('open', (event) => {
            console.log('WebSocket connection opened:', event);
        });

        socket.addEventListener('message', (event) => {
            console.log('WebSocket message received:', event.data);
        });

        socket.addEventListener('close', (event) => {
            console.log('WebSocket connection closed:', event);
        });

        document.getElementById('send-btn').addEventListener('click', () => {
            const message = document.getElementById('message-input').value;
            socket.send(message);
        });
    </script>
</head>
<body>
    <input type="text" id="message-input">
    <button id="send-btn">Send</button>
</body>
</html>

Multi-Client Communication

To enable communication between multiple clients, maintain a list of connected clients on the server and broadcast messages to all other clients when a message is received.

const clients = new Set();

app.ws.use(async (ws, ctx) => {
    // Triggered when a WebSocket connection is established
    ws.on('message', (message) => {
        console.log(`Received: ${message}`);
        // Broadcast message to all other clients
        clients.forEach(client => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(`Broadcast: ${message}`);
            }
        });
    });

    // Triggered when the WebSocket connection is closed
    ws.on('close', () => {
        console.log('Connection closed');
        clients.delete(ws);
    });

    // Add the newly connected client to the list
    clients.add(ws);
});

Keeping the Connection Alive

WebSocket connections may disconnect due to network issues. You can implement a heartbeat mechanism to monitor connection status and ensure the connection remains active.

const HEARTBEAT_INTERVAL = 10000; // Heartbeat interval in milliseconds
const PING_DATA = 'ping'; // Heartbeat data

app.ws.use(async (ws, ctx) => {
    // Periodically send heartbeat data
    setInterval(() => {
        ws.send(PING_DATA);
    }, HEARTBEAT_INTERVAL);

    // Listen for heartbeat responses
    ws.on('message', (message) => {
        if (message === PING_DATA) {
            // Heartbeat response received, no action needed
        } else {
            console.log(`Received: ${message}`);
            // Broadcast message to all other clients
            clients.forEach(client => {
                if (client !== ws && client.readyState === WebSocket.OPEN) {
                    client.send(`Broadcast: ${message}`);
                }
            });
        }
    });

    // Triggered when the WebSocket connection is closed
    ws.on('close', () => {
        console.log('Connection closed');
        clients.delete(ws);
    });

    // Add the newly connected client to the list
    clients.add(ws);
});

Error Handling

When handling WebSocket connections, you need to properly manage potential errors, such as connection timeouts or data parsing errors.

app.ws.use(async (ws, ctx) => {
    // Triggered when a WebSocket connection is established
    ws.on('message', (message) => {
        try {
            console.log(`Received: ${message}`);
            // Broadcast message to all other clients
            clients.forEach(client => {
                if (client !== ws && client.readyState === WebSocket.OPEN) {
                    client.send(`Broadcast: ${message}`);
                }
            });
        } catch (error) {
            console.error('Error processing message:', error);
        }
    });

    // Triggered when the WebSocket connection is closed
    ws.on('close', () => {
        console.log('Connection closed');
        clients.delete(ws);
    });

    // Add the newly connected client to the list
    clients.add(ws);
});

Implementing a Custom Protocol

In WebSocket, you can define a custom communication protocol for more precise data transmission and command control. For example, you can create a simple JSON protocol to handle different message types.

Server Side:

app.ws.use(async (ws, ctx) => {
    ws.on('message', (message) => {
        try {
            const data = JSON.parse(message);
            switch (data.type) {
                case 'chat':
                    broadcastMessage(data.content);
                    break;
                case 'join':
                    joinRoom(data.roomId);
                    break;
                default:
                    console.error('Unknown message type');
            }
        } catch (error) {
            console.error('Error parsing message:', error);
        }
    });
});

Client Side:

socket.addEventListener('open', () => {
    socket.send(JSON.stringify({ type: 'join', roomId: 'room1' }));
});

document.getElementById('send-btn').addEventListener('click', () => {
    const message = document.getElementById('message-input').value;
    socket.send(JSON.stringify({ type: 'chat', content: message }));
});

Rooms and Channels

In multi-user scenarios, you may need to support rooms or channels to group users and limit message propagation.

Server Side:

const rooms = {};

function joinRoom(roomId) {
    if (!rooms[roomId]) {
        rooms[roomId] = new Set();
    }
    rooms[roomId].add(this);
}

function leaveRoom(roomId) {
    if (rooms[roomId]) {
        rooms[roomId].delete(this);
    }
}

function broadcastMessageToRoom(roomId, message) {
    if (rooms[roomId]) {
        rooms[roomId].forEach(ws => {
            if (ws.readyState === WebSocket.OPEN) {
                ws.send(message);
            }
        });
    }
}

app.ws.use(async (ws, ctx) => {
    ws.joinRoom = joinRoom.bind(ws);
    ws.leaveRoom = leaveRoom.bind(ws);

    ws.on('message', (message) => {
        try {
            const data = JSON.parse(message);
            if (data.type === 'join') {
                ws.joinRoom(data.roomId);
            } else if (data.type === 'chat') {
                broadcastMessageToRoom(data.roomId, `Chat: ${data.content}`);
            }
        } catch (error) {
            console.error('Error parsing message:', error);
        }
    });

    ws.on('close', () => {
        console.log('Connection closed');
        for (const roomId in rooms) {
            ws.leaveRoom(roomId);
        }
    });
});

Client Side:

socket.addEventListener('open', () => {
    socket.send(JSON.stringify({ type: 'join', roomId: 'room1' }));
});

Sessions and Authentication

To ensure the security of WebSocket connections, you may need to implement session management and authentication. You can use JWT or session IDs to identify and verify users.

Server Side:

app.ws.use(async (ws, ctx) => {
    const sessionId = ctx.cookies.get('session-id');
    const user = await getUserBySession(sessionId);
    if (!user) {
        ws.close();
        return;
    }
    // User is authenticated, proceed with handling
});

Client Side:

socket.addEventListener('open', () => {
    socket.send(JSON.stringify({ type: 'authenticate', token: 'jwt-token' }));
});

Performance Optimization

WebSocket performance can be optimized in various ways, such as enabling compression, reducing unnecessary data transfers, and utilizing caching effectively.

Server Side:

const wss = new WebSocket.Server({ server: app.server });
wss.options.perMessageDeflate = true; // Enable compression

Client Side:

const socket = new WebSocket('ws://localhost:3000', { perMessageDeflate: true });

Error Recovery and Reconnection

WebSocket connections may disconnect due to various reasons. Implementing error recovery and automatic reconnection can enhance application robustness.

Client Side:

socket.addEventListener('error', (event) => {
    console.error('WebSocket error:', event);
    setTimeout(() => {
        socket.close();
        socket = new WebSocket('ws://localhost:3000');
    }, 5000);
});

Security

In addition to session management and authentication, consider other security measures such as using HTTPS, limiting concurrent connections, and preventing Denial-of-Service (DoS) attacks.

Server Side:

const https = require('https');
const fs = require('fs');

const httpsOptions = {
    key: fs.readFileSync('path/to/private.key'),
    cert: fs.readFileSync('path/to/cert.pem')
};
const server = https.createServer(httpsOptions, app.callback());
const wss = new WebSocket.Server({ server });

app.ws.use(async (ws, ctx) => {
    // WebSocket handling logic
});

server.listen(3000, () => {
    console.log('Server is listening on https://localhost:3000');
});
Share your love