Ad

Hundreds Of Polling Requests Coming From Socket.io, App Really Slow

I'm creating a real time chat app with socket.io, express and React. My issue is that I get hundreds of polling requests until my browser basically crashes, I have no idea why.

I've tried to put a polling duration, a close timeout, a heartbeat interval, I've checked, both my socket.io and socket.io-client are on the same version.. I've tried everything could find on the web but nothing works. I'm sure it's just a stupid little mistake that I just can't find, if you could help that would be great, thanks!

Here's my code :

import express from "express";
import socketio from 'socket.io';
import path from 'path';
import ioCookieParser from 'socket.io-cookie-parser'
import http from 'http';

const app = express()
const port = process.env.PORT || 8000
app.set("port", port)

const httpServer = new http.Server(app);

const io = socketio(httpServer);
io.use(ioCookieParser(secret));

io.on('connection', function (client) {
    const userId = client.request.signedCookies._session;

    const clients = new Map();
    client.on('login', () => {
        clients.set(userId, { client })
        console.log("clients :", clients)
    })
    client.on('message', (message) => {
       User.findById(userId, function(err, obj) {
        if(err) {
            console.log(err);
            return null
        }
        let currentUser = obj["email"];
        client.broadcast.emit("received", { message, currentUser });
        Connect.then(db  =>  {
                console.log("connected correctly to the server");
                let  chatMessage  =  new Chat({ message: message, sender: currentUser});
                chatMessage.save();
            });
        })
    })

    client.on('error', function (err) {
        console.log('received error from client:', client.id)
        console.log(err)
    })
});

Here is an example of a request :

GET  localhost:8000 /socket.io/?EIO=3&transport=polling&t=Mideit5&sid=OxvoE0uJbi9DZyk-AAt8  xhr             

Thanks!

Ad

Answer

My issue was that, in the React component, I was declaring :

const socket = io.connect('http://localhost:8000')

inside the component.

I've moved this constant outside of the component and now the issue is solved!

Ad
source: stackoverflow.com
Ad