socket.io does not close previous connection - node.js

we have this socket.io serverside that on auth joins the user in the rooms he is in, but on disconnect it seems like it does not really disconnect, because on a new connect i get 2 connections, seen in screenshot. Also included is the disconnect code part.
connection part:
io.on("connection", function(socket) {
console.log("connected");
console.log("user connected with " + socket.id);
disconnect part:
socket.on("disconnect", function() {
socket.removeAllListeners();
if (socket.auth) {
socket.groups.forEach(group => {
console.log("left " + group.chatGroupID);
socket.leave(group.chatGroupID);
});
}
delete socket[socket.id];
socket.disconnect(true);
console.log(socket.disconnected);
console.info("disconnected user (id=" + socket.id + ").");
});
server printout:

somehow i globbed all files in my folder sockets and thus nested my sockets which caused this weird behavior

Related

socket.io client can't connect/reconnect reliably

I am utilizing socket.io V3.1.1 and am trying to figure out how to get the client to reconnect after the connection is disconnected due to a phone going asleep. When I run the code, it connects, refreshes an order, and then I press the power button on the iPhone to cause it to sleep. I then press the home key, and I see a disconnect event, followed by a connect event which refreshes the order. If I repeat the process, I see it disconnect, but I never see a connect event.
The question is, how does one reliably connect/reconnect and/or why don't I get additional connect events?
Here's a sample console.log output:
connect
refreshOrder 1234
disconnect due to transport error
connect
refreshOrder 1234
disconnect due to transport error
and then no more events
Here's the primary code that's involved:
const socket = io("wss://xyz.org:3000");
socket.on('connect', () => {
console.log("connect");
if (order_id !== null){
refreshOrder(order_id);
}
});
socket.on("disconnect", (reason) => {
console.log("disconnect due to " + reason);
socket.connect();
});
I also have the following event handlers, but they never get called:
socket.on('reconnect', () => {
console.log('reconnect');
if (order_id !== null){
refreshOrder(order_id);
}
});
socket.on("connect_error", (err) => {
console.log("connect_error: " + err);
setTimeout(() => {
console.log("socket.connect retry");
socket.connect();
}, 1000);
});
The answer is that you should ignore the disconnect and let the built-in reconnect code handle it. I believe that my problem was that I had looked at examples of pre-V3 code and didn't understand that it was handled differently in V3. So, a better disconnect event handler would be
socket.on("disconnect", (reason) => {
console_log("disconnect due to " + reason);
if (reason === "io server disconnect") {
// disconnect initiated by server. Manually reconnect
socket.connect();
}
});

Why does socket.io not join a given room?

I'm having problems when I try to join a socket to a room. The name of the room is the socket.id and it is assigned when it is connected. But when this happens it doesn't join to room. What could be the error?
Client code:
var socket = io();
socket.on("connect", function() {
socket.emit("joinRoom", socket.id);
});
socket.on("agentMessage", function(msg) {
$('#messages').append("<div class='agent-messages'><p>" + msg + "</p></div>");
});
Server code:
io.on("connection", (socket) => {
let roomID;
socket.on("joinRoom", (socket_id) => {
roomID = socket_id;
socket.join(roomID);
socket.to(roomID).emit("agentMessage", "Welcome!");
});
socket.on("disconnect", () => {
socket.leave(socket_id);
});
});
Your client is actually joining the room, but it is not sending the message. As you are sending message from the server side you cannot send it using the socket, as socket represents a client connection and cannot throw events on behalf of server. You have to use
io.to(roomID).emit("agentMessage", "Welcome!");
as io represents a server instance and can throw events on behalf of server(actually it is the server).
Reference

Multiple socket clients gets disconnected [socket.io]

Lets say..I have a two clients connected.
https://i.stack.imgur.com/90IlV.png
So as soon as i refresh any one of the browser both clients get disconnected..
https://i.stack.imgur.com/oZx99.png
and I have written code to remove socket if of the user that gets disconnected.
let userId = socket.request._query['userId'];
socket.on('disconnect', function(){
console.log("disconnect: ", socket.id);
User.removeSocketId(userId, (err, res) => {
if(err) throw err;
//updated code and found this emit was causing the issue, without this code everything work fine.
socket.broadcast.emit('chat-list-response',{
error : false ,
userDisconnected : true ,
socketId : socket.id
});
});
});
So because of this socket ID of both clients gets removed.
Is there any way to stop that multiple disconnection ??
Thanks in advance.

How to configure socket io and socket io client

Good day
I need to connect a lot of pc's to a main server, through a server of units
I have something but I don't have all complete
Main Server
socketIo = require("socket.io"),
ioServer = socketIo(server),
ioServer.sockets.on("connection",function(socket){
// Display a connected message
console.log("Server-Client Connected!");
// When we receive a message...
socket.on("message",function(data){
// We got a message... I dunno what we should do with this...
console.log(data);
console.log(data.from + " is connected with ip " + data.ip);
socket.emit('message', { 'from': '10.19.17.101', 'answer':'I already added you '+data.from });
});
});
Server Units
socketIo = require("socket.io"),
ioServer = socketIo(server),
ioClient = require("socket.io-client")('http://10.19.17.101:7700')
ioClient.on('connect', function(){
ioClient.on('message',function(data){
console.log(data.from + " answered: " + data.answer);
ioServer.to('pxe4').emit('message',data);
});
ioClient.emit('message',{ 'from': 'pxe4', 'ip':'10.19.16.84' });
});
ioServer.sockets.on("connection",function(socket){
// Display a connected message
console.log("User-Client Connected!");
// When we receive a message...
socket.on("message",function(data){
// We got a message... I dunno what we should do with this...
console.log(data);
console.log(data.from + " is connected with ip " + data.ip);
socket.emit('message', { 'from': '10.19.16.84', 'answer':'I already added you '+data.from });
ioClient.emit("message",data);
});
socket.on("disconnect",function(data){
// We need to notify Server 2 that the client has disconnected
ioClient.emit("message","UD,"+socket.id);
// Other logic you may or may not want
// Your other disconnect code here
});
});
Units
ioClient = require("socket.io-client")('http://10.19.16.84:7770'),
ioClient.on('connect', function(){
ioClient.on('message',function(data){
// We received a message from Server 2
// We are going to forward/broadcast that message to the "Lobby" room
console.log(data.from + " answered: " + data.answer);
});
ioClient.emit('message',forsend);
});
I was wondering if at this moment I can send some information from Main Server to a specific unit?
If someone could help me, I will be thankful.
When connecting from each client on the main server or Server Units you recive a socket object which contains socketid. You have to save those socket id's in some data storge for speedy access with the server information. When you have to emit data to specific socket you have to query that specific socket from data storage and emit the data. On disconnect you have to pull that particular socket from data storage

Socket.io - method leave doesn't work

I'm creating an online chat on my website.
Almost everything is okay: a client can join a room, he can talk with other clients in the room BUT he can't leave it.
Indeed, when a client try to disconnect a room, it doesn't work.
Here is my server-side code:
io.sockets.on('connection', function (socket) {
// connection
socket.on('room', function(room) {
socket.join(room);
console.log('room join :'+room);
});
// some actions (message, etc)
// disconnection
socket.on('leave', function(room) {
socket.leave(room);
console.log('room quit :'+room);
});
});
I get the "room quit : xxx" in my console but when I try to talk in the room, that still works!
My client can't be disconnected from the room. What goes wrong?

Resources