简体   繁体   English

Socket.io - 如何在接收消息前检查消息大小,如果大于 1MB 则拒绝?

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

I'm new to Socket.io我是Socket.io的新用户

I'm programming an online browser game in Node.JS with a chat application我正在使用聊天应用程序在Node.JS中编写在线浏览器游戏

And I want to limit the message size to 1MB and reject if it's bigger than that我想将消息大小限制为1MB ,如果大于则拒绝

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但是即使是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:在创建套接字服务器的位置使用“maxHttpBufferSize”属性设置最大消息大小,您可以这样做:

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希望这对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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