I have encountered a peculiar issue with my code. It involves emitting from the server side and listening on the client side. The connection seems to persist indefinitely, even when the client refreshes or exits the page. However, the code on the client side does not execute and no errors are being displayed in the logs.
ServerSide Code:
io.on('connection', function(socket) {
console.log("New socket connection");
socket.on('joinApp', ({msg, password}) =>{
let username;
let rooms;
model.findOne({username: msg}, function(err, found){
if(!err){
var checka = false;
if(found){
if(found.password === password){
user = userLogged(socket.id, msg, found.rooms);
username = getUserName(socket.id).username;
rooms = getUserName(socket.id).rooms;
console.log(msg + " Has entered the chat");
console.log(socket.id);
checka = true;
}else{
console.log("Incorrect password");
}
}else{
console.log("User not found");
}
io.to(socket.id).sockets.emit("checker", checka);
}
});
socket.on('myRooms', () =>{
let user = getUserName(socket.id);
let username = user.username;
let rooms = user.rooms;
if(user.rooms.length === 0){
console.log(username + " You have no rooms");
socket.emit("yourRooms", {username, rooms});
}else{
}
});
socket.on('disconnect', () => {
console.log("Disconnected");
});
});
});
This is the code I am using in my Express.js file. In particular, this line has been causing issues:
io.to(socket.id).emit("yourRooms", {username, rooms});
The problem lies here - I emit the signal expecting the client to listen to it (Clientside code below):
let title = document.getElementById("title");
let rooms = document.getElementById("rooms");
console.log(socket.id);
socket.on("yourRooms", (username, rooms) => {
if(rooms.length === 0){
rooms.innerHTML = "You have no rooms";
}
title.innerHTML = user + "'s rooms";
});
This section of the code correctly displays the socket.id
of the client, indicating no issues.
console.log(socket.id);
I refrained from declaring another socket instance as that approach did not yield results.
In another part of my code, following this exact practice works fine. This exists in the file where I initialized my socket instance:
const socket = io();
I have spent hours troubleshooting but have not come across any errors in the logs. Additionally, the socket.id
appears correct when logged in the problematic clientside script. I'm unsure of what mistake I might be making.