簡體   English   中英

Socket.io - 如何在接收消息前檢查消息大小,如果大於 1MB 則拒絕?

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

我是Socket.io的新用戶

我正在使用聊天應用程序在Node.JS中編寫在線瀏覽器游戲

我想將消息大小限制為1MB ,如果大於則拒絕

這是我的代碼:

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;

    });

});

但是即使是100MB ,服務器也會繼續接收消息

我想在收到整個消息之前拒絕它

在創建套接字服務器的位置使用“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}`);
});

但是有一個原因。 服務器不會收到大於大小限制的消息。

希望這對你有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM