Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS socket.IO disconnects when sending large Json

I'm writing a multilayer card game (like hearthstone) with Nodejs back-end and an angular front-end.

I tried to connect the two with Socket.IO, but it turned out that if I send a JSON object over about 8000char(the gameState object), then the client just keeps disconnecting and reconnecting.

If I only send the substring of 6000 char of the object everything is fine, but it crashes over 8000(I need about 20 000)

I have only tried in localhost

Here is the backend:

    constructor() {
    this.app = express();
    this.port = process.env.PORT || ChatServer.PORT;
    this.server = createServer(this.app);
    this.io = socketIo(this.server);
    this.gameService = new GameService();
    this.listen();
}

listen(): void {
    this.server.listen(this.port, () => {
        console.log('Running server on port %s', this.port);
    });

    this.io.on('connect', (socket: any) => {
        console.log('Connected client on port %s.', this.port);
        socket.on('message', (m: string) => {
            console.log('[server](message): %s', JSON.stringify(m));
            this.io.emit('message', JSON.stringify(this.gameService.getGameState()).substring(1, 6000));
        });

        socket.on('disconnect', () => {
            console.log('Client disconnected');
        });
    });
}

Edit:It works perfectly well with ajax, but I would need sockets

like image 947
Ez Az Avatar asked Jun 27 '26 18:06

Ez Az


1 Answers

Socket.io has a default value of 1 MB (v3 onwards) as the maximum data size that it can receive. For v2 and before, this value used to be 100 MB.

You can use maxHttpBufferSize to increase the maximum size of data packet that you want to receive when creating the server.

const io = require("socket.io")(httpServer, {
    maxHttpBufferSize: 1e8    // 100 MB
});

According to the migration docs:

  • the client is disconnected when sending a big payload (> 1MB)

This is probably due to the fact that the default value of maxHttpBufferSize is now 1MB. When receiving a packet that is larger than this, the server disconnects the client, in order to prevent malicious clients from overloading the server.

You can adjust the value when creating the server:

like image 194
Stainlee Bakhla Avatar answered Jun 30 '26 12:06

Stainlee Bakhla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!