简体   繁体   中英

Socket.io - How to check message size before receiving it, And reject if it's bigger than 1MB?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM