kartikk221 / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
1.79k stars 97 forks source link

Websocket only returns type string #299

Closed ArthurTimmermans closed 1 month ago

ArthurTimmermans commented 1 month ago

Hello everyone,

I have created a web socket on hyper-express (version 6.17.2) and have the issue that messages are always recognised as type 'string' while I send for example Binary data. CleanShot 2024-09-20 at 16 50 11

Is this a known issue or something related to my code?

Message send via Postman: CleanShot 2024-09-20 at 16 39 37@2x

Backend Code


const webserver = new HyperExpress.Server();

webserver.get('/', (request, response) => {
    response.status(200).send("Hello world");
})

// WebSocket route 
webserver.ws('/stream', {max_payload_length: 5 * 1024 * 1024 }, (ws) => {
    console.log('Socket connection opened.');

    ws.on('message', (message) => {
        console.log('Type of message:', typeof message); //Gives type of message
        if (Buffer.isBuffer(message)) {
            // This will check if the data is binary (received as Buffer in Node.js)
            console.log('Received binary data (Buffer):');
        } else {
            console.log('Received non-binary data:');
        }
    });
    ws.on('close', (code, reason) => {
        console.log(`WebSocket connection closed. Code: ${code}, Reason: ${reason}`);
    });
});
webserver.listen(6060)
    .then((socket) => console.log("Webserver started on port 6060"))
    .catch((error) => console.log("Failed to start webserver on port 6060"))````
kartikk221 commented 1 month ago

Hi, please review the docs for Router and you will find that when binding Router.ws() to create a route, you can specify a message_type option alongside other route options which will dictate the type of the data.

So essentially you can change the default string parsing behavior by defining the message_type option alongside max payload length and others.