1

I'm new to Socket.io

I'm programming an online browser game in Node.JS with a chat application

And I want to limit the message size to 1MB and reject if it's bigger than that

This is my code:

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, { cors: { origin: "*" } });
const PORT = process.env.PORT || 3001;
const cors = require("cors");

// ... some code ...

io.on('connection', (socket) => {

    // ... some code ...

    socket.on("chat-message", message => {

        // I did something like this:
        if (message.length > 1000000) return;

    });

});

But the server keeps receiving the message even if it's 100MB

I want to reject it before receiving the whole message

Mr_NAIF
  • 96
  • 6
  • 1
    This question has been asked [before](https://stackoverflow.com/questions/21706181/socket-io-how-to-limit-the-size-of-emitted-data-from-client-to-the-websocket-se) with no good solution. I won't mark this one as a dup because that was 2015 so maybe something has changed since then. And, here's a [related question](https://stackoverflow.com/questions/54125552/handling-oversized-messages-with-socket-io) (also with no answer). – jfriend00 Aug 14 '21 at 08:09

1 Answers1

1

where you create your socket server use the "maxHttpBufferSize" property to set the maximum message size, you can do it like this:

const express = require('express');
const http = require('http');
const { Server } = require("socket.io");
const app = express();
const server = http.createServer(app);

// here, we have set the maximum size of the message to 10
// which you can see using the ".length" property on the string
const socketServer = new Server(server, {
    maxHttpBufferSize: 1e1
});

const port =  9000;
server.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

but there is one down to it. messages bigger than the size limit are not recieved by the server.

hope this helps you