Socket IO makes multiple connections when the page is refreshed - Node JS
Solution 1
Getting multiple messages
Here are some thumb rules for socketio
-
if you listen to any event once, you'll get the message once in the callback
-
if you listen to any event twice, you'll get the message twice in the callback
-
if you listen to any event nth time, you'll get the message nth in the callback
-
If you're listening to any event on page load, don't forget to
listen off
that event before you leave the page (if an event is not globally)- If you forgot to
listen off
and if you again re-visit page. you'll start listening to events multiple times. because on page load you're listening to the event. and the previous event is not yet stopped bylisten off
- If you forgot to
-
Don't listen to any event in
loop
, It may listen to it multiple time and you'll get multiple messages on a single change.
connect socket
const socket = io('http://localhost', {
transports: ['websocket'],
upgrade: false
});
listen and listen off an event
let onMessage = (data) => {
console.log(data);
}
//listen message
socket.on('message', onMessage);
//stop listening message
socket.off('message', onMessage);
remove all listeners on disconnect
socket.on('disconnect', () => {
socket.removeAllListeners();
});
Use Firecamp to test/debug SocketIO events visually.
Solution 2
i was having the problem that each client was getting two socket connections. I thought something is wrong with sockets. but the problem was
- FrontEnd -> React
- Created the template using create-react-app
- In index.js file it uses something called React.StrictMode
- This mode renders some of the App.js components two times.
- Just remove that React.StrictMode and try to see if your problem is solved.
Nadeem Ahmad
Experienced Software Engineer with 7 years of experience designing, developing and deploying robust code for high-volume businesses in a highly collaborative, agile and fast-paced environment. Possesses excellent communication skills, bringing forth extensive experience in performing research on product development processes and offering solutions and alterations to improve performance and scalability. I always have the pleasure to acquire valuable knowledge, diversified skills, strong leadership and managerial capabilities to complement.
Updated on July 10, 2022Comments
-
Nadeem Ahmad almost 2 years
I have developed a scrapping tool, that scraps jobs from all websites and save them into the database. I have made my own default log where I get messages(errors, info) etc. I am using socket.io to update my view in real time and for database too.
The problem is when I start the app it perfectly get make socket, and database connections. But when I try to refresh the page, the same connection is made again twice with the same message and different ID's. As much I refresh the page the connections are made, and the id get changed, but for all made connection they use one ID,
Below is the Log which shows it :
I have uploaded this video, please check this as well. Try to watch the very beginning, and then at
01:41
and03:06
, before starting scrapping of the first site the connection is established, but when second website scrapping is started, theInternet Connection
message is given twice, and the same stands for when third website scrapping is started, the number of messages get doubled every time. I don't know why.I have tried following the answer of this question, but still no success. The code is 600+ lines on
server
file, and 150+ lines second file and same on the client side, that's why I can't upload all and it's a bit confidential.But the socket connection on the client and server is like this:
Server Side
const express = require("express"); const app = express(); const scrap = require("./algorithm"); const event = scrap.defEvent;//imported from another file const ms_connect = scrap.ms_connect; const server = app.listen(8000, function(){ console.log('Listening on 8000'); }); const io = require("socket.io").listen(server); const internetAvailable = require("internet-available"); app.use(express.static(__dirname + "/")); app.get("/scrap",function(req,res){ res.sendFile(__dirname+"/index.html");//Set the Default Route io.on("connection",function(socket){ //On Socket Connection socketSameMess("Socket",'Sockets Connection Made on ID : <span style="color:#03a9f4;">'+socket.id+'<span>'); ms_connect.connect(function(err){//On Connection with Database if(err) socketSameMess("database_error",err+" "); // If any error in database connection socketSameMess("Database ",'Connected to MYSQL Database Successfully...'); }) }) }) function eventSameMess(auth,mess){ //hits the custom console defEvent.emit("hitConsole",{a:auth,m:mess}); }
Client Side
var socket = io.connect('http://localhost:8000'); socket.on('connect',function(){ if(socket.connected){ initDocument(); } })