I am trying to build a small lobby system with socket.io, but I recently encountered a problem when a user closes a tab to leave the lobby. I want to have instant (or at least close to instant) feedback on the client-side when the user disconnects from the lobby.
Unfortunately, it always takes about 35 sec between closing a browser tab and the socket.on('disconnect') event firing on the server, which is too long for what I need.
I already did some research and found out, that the connection gets closed instantly when the reason of closure is a transport close or a transport error.
In my case it seems to be a ping timeout, which means that socket.io waits some time until the next package gets sent. If that doesn't happen, the connection will be closed.
So my question now is, why does the ping timeout reason take place here when closing a tab, and how can I change that to a transport close reason?
My current code looks like this:
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const formatMessage = require('./utils/messages');
const {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers
} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Run when client connects
io.on('connection', socket => {
socket.on('joinRoom', ({ username, room }) => {
const user = userJoin(socket.id, username, room);
socket.join(user.room);
console.log("ROOMS AFTER JOIN: ", io.sockets.adapter.rooms);
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
// Runs when client disconnects
socket.on('disconnect', (reason) => {
const user = userLeave(socket.id);
console.log("Reason: ", reason)
if (user) {
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));