Socket.io: How to limit the size of emitted data from client to the websocket server

后端 未结 5 953

I have a node.js server with socket.io. My clients use socket.io to connect to the node.js server.

Data is transmitted from clients to server in the following way:

5条回答
  •  不要未来只要你来
    2021-01-11 14:19

    Probably you may consider switching to socket.io-stream and handle input stream directly.

    This way you should join chunks and finally parse json input manually, but you have chance to close connection when input data length exceeds threshold you decide.

    Otherwise (staying with socket.io approach) your callback won't be called until whole data stream were received. This doesn't stop your js main thread execution, but waste memory, cpu and bandwith.

    On the other hand, if your only goal is to avoid overload of your processing algorithm you can continue limitting it by counting elements in the received object. For instance:

    if (Object.keys(data).length > n) return; // Where n is your maximum acceptable number of elements.
    // But, anyway, this doesn't control the actual size of each element.
    

提交回复
热议问题