Ultimate Guide to uWS Fast and Efficient WebSockets

Introduction to uWS – Fast and Efficient WebSockets

uWebSockets (uWS) is a highly efficient, scalable, and lightweight WebSocket library written in C++. It is designed to handle high-throughput without sacrificing performance, making it an excellent choice for real-time web applications.

API Examples

In this section, we’ll explore some of uWS’s most useful APIs.

Creating a WebSocket Server


const uWS = require('uWebSockets.js');
uWS.App().ws('/*', {
    /* Options */
    compression: uWS.SHARED_COMPRESSOR,
    maxPayloadLength: 16 * 1024 * 1024,
    idleTimeout: 30,
    /* Handlers */
    open: (ws, req) => {
        console.log('A WebSocket connected!');
    },
    message: (ws, message, isBinary) => {
        /* Use our efficient sending methods */
        ws.send(message, isBinary);
    },
    close: (ws, code, message) => {
        console.log('A WebSocket disconnected!');
    }
}).listen(9001, (token) => {
    if (token) {
        console.log('Listening to port 9001');
    } else {
        console.log('Failed to listen to port 9001');
    }
});

HTTP Server with WebSocket Support


const uWS = require('uWebSockets.js');
uWS.App().get('/hello', (res, req) => {
    res.end('Hello World!');
}).ws('/*', {
    open: (ws, req) => {
        ws.send('Hello WebSocket Client!');
    }
}).listen(9001, (token) => {
    if (token) {
        console.log('Listening to port 9001');
    } else {
        console.log('Failed to listen to port 9001');
    }
});

Handling Backpressure


const uWS = require('uWebSockets.js');
uWS.App().ws('/*', {
    message: (ws, message, isBinary) => {
        if (ws.getBufferedAmount() < 16 * 1024 * 1024) {
            ws.send(message, isBinary);
        } else {
            console.log('Backpressure, slow down sending!');
        }
    }
}).listen(9001, (token) => {
    if (token) {
        console.log('Listening to port 9001');
    } else {
        console.log('Failed to listen to port 9001');
    }
});

Broadcasting Messages


const uWS = require('uWebSockets.js');
let clients = [];
uWS.App().ws('/*', {
    open: (ws, req) => {
        clients.push(ws);
    },
    message: (ws, message, isBinary) => {
        for (let client of clients) {
            client.send(message, isBinary);
        }
    },
    close: (ws, code, message) => {
        clients = clients.filter(client => client !== ws);
    }
}).listen(9001, (token) => {
    if (token) {
        console.log('Listening to port 9001');
    } else {
        console.log('Failed to listen to port 9001');
    }
});

Integrating WebSocket and HTTP


const uWS = require('uWebSockets.js');
uWS.App().get('/status', (res, req) => {
    res.end('Server is running!');
}).ws('/chat', {
    open: (ws, req) => {
        ws.send('Welcome to the chat!');
    },
    message: (ws, message, isBinary) => {
        /* Handle incoming chat messages */
        // Broadcast the message
        app.publish('broadcast', message, isBinary);
    },
    close: (ws, code, message) => {
        console.log('A WebSocket disconnected!');
    }
}).listen(9001, (token) => {
    if (token) {
        console.log('Listening to port 9001');
    } else {
        console.log('Failed to listen to port 9001');
    }
});

Application Example

Let’s build a simple chat app that uses uWS for WebSocket communication.


const uWS = require('uWebSockets.js');
const clients = new Set();
uWS.App().ws('/*', {
    open: (ws) => clients.add(ws),
    message: (ws, message, isBinary) => {
        for (let client of clients) {
            if (client !== ws) {
                client.send(message, isBinary);
            }
        }
    },
    close: (ws) => clients.delete(ws)
}).listen(9001, (token) => {
    if (token) console.log('Listening to port 9001');
    else console.log('Failed to listen to port 9001');
});

Here, a simple uWS-based WebSocket server is set up. Clients can connect, and any message sent by one client is broadcast to all other connected clients, implementing a basic chat functionality.

Utilize uWS to build efficient, high-performance real-time applications.

Hash: 158850fbccadf9aaa3ed92fd26feac43b7ff66f0153df446bbef4ffa506f91fb

Leave a Reply

Your email address will not be published. Required fields are marked *