socket.io-client
socket.io-client copied to clipboard
Socket keeps connecting and disconnecting in web app
Describe the bug
I've a web based chat application. A doctor logs in from laptop (Chrome on Windows 10) where he can see the patients in a queue. Patients join from mobile browser (Chrome on Android or Safari on iOS). Patients wait in queue unless doctor initiates a chat with patients one by one.
While patients are waiting in the queue, they start using other apps on mobile and web browser goes in background. After few minutes (it varies from 1 to 5 minutes) patient disconnects from queue and after few minutes reconnects automatically (browser is still in background).
This way patients keep switching in/out the queue and doctor is not able to talk them smoothly.
To Reproduce
-
Open Socket.io Chat Demo
-
Join as USER-1 from laptop/computer (e.g. Chrome on Windows).
-
Join as USER-2 from mobile browser (e.g. Chrome on Android).
-
Minimize the browser on mobile and open any other app. Use it for a while (1 to 10 min).
-
USER-2 will disconnect and reconnect again and again
Expected behavior
Connection on mobile browser should remain active. It should not chop again and again.
Platform:
- Device: Samsung A30S
- OS: Android 10
- Web Browser: Chrome
For me it helped to downgrade to socket.io-client version 2.4.0
@zubair1103 I think you shouldn't rely on the status of the Socket.IO connection for your queue:
- browser may put an inactive tab to sleep in order to save battery
- users may loose connection (especially true on browsers)
In fact, there are quite a lot of things that might kill your TCP connection.
@bwiessneth I'm not sure how downgrading to version 2.x can help here. Could you please explain?
@darrachequesne I cannot explain why and have not found the reason for it, but downgrading from 3.x to 2.4.0 resolved my continuous connects and disconnects without changing anything on the server-side. I am using socket.io-client in a react app connecting via websocket-transport to a python/flask-socketio server.
@bwiessneth in that case, might it be linked to your version of the flask-socketio server? The compatibility table can be found here: https://flask-socketio.readthedocs.io/en/latest/#version-compatibility
Downgrading in my case might not be helpful as I am already using a lower i.e. 2.3 @ both server & client.
@darrachequesne as you suggested to not rely on Socket.IO connection; how can we know that a patient has actually closed the browser or we explicitly closed connection by some logic?
If 2.4 worked for @bwiessneth then I'll try to upgrade to 2.4.
Downgrade to 2.3.1 both server and client will work, it worked for me :)
Delete folder node_modules and downgrade to "socket.io-client": "^2.3.0" (packages.json) then run yarn install
again, it will work. This is a @bug!
Hi @zubair1103. I am dealing with the same issue using v2.3.0 in an extension that run in whatsappweb. Upgrade to 2.4.x solves the problem?
Updating to 2.4.0 does not solves the problem, as you see, the first connection keep alive for 6.5 mins, and then starts to disconnect every 1 - 2 mins. (always if chrome tab is in background)
Hi @NahuBocco
No, unfortunately it did not resolve the issue.
However I managed it by setting ping interval & timeout value. Now it is working better in my case.
import createIO from 'socket.io';
const io = createIO(server, {
transports: ['websocket'],
pingInterval: 1000 * 60 * 5,
pingTimeout: 1000 * 60 * 3
})
Any idea why the downgrade is necessary?
Hi @NahuBocco
No, unfortunately it did not resolve the issue.
However I managed it by setting ping interval & timeout value. Now it is working better in my case.
import createIO from 'socket.io'; const io = createIO(server, { transports: ['websocket'], pingInterval: 1000 * 60 * 5, pingTimeout: 1000 * 60 * 3 })
not working for me
Hi @NahuBocco No, unfortunately it did not resolve the issue. However I managed it by setting ping interval & timeout value. Now it is working better in my case.
import createIO from 'socket.io'; const io = createIO(server, { transports: ['websocket'], pingInterval: 1000 * 60 * 5, pingTimeout: 1000 * 60 * 3 })
not working for me
It seems that you set pingInterval & pingTimeout on client side while making a connection. It worked for me by setting on server side while creating an io server.
Any updates on this? I have tried downgrading but that doesn't work, updating the pinginterval and timeout just makes it non responsive. Any ideas on how to solve this issue?
I don't believe is a good idea to set the ping interval to 5 minutes and ping timeout to 3 minutes.
You're assuming during the 5 minutes your users will not disconnect from the network, "Wake up throttling" will not take effect on the background tab/app, and sometimes the device could turn off by battery. Then if something of previous scenarios happens you need to wait 3 minutes to detect ping-timeout
or transport close
. In fact, maybe you will want to emit events between users, but during your 5 minutes of interval, you assume they will receive, but not.
In terms of the suggestion of @bwiessneth
For me it helped to downgrade to socket.io-client version 2.4.0
Don't do it because from v4 the ping was reverted from server to client, so with this, you will avoid ping-timeout
by Wake up throttling or with the app in the background.
We're dealing with this now, but don't have more info about how to resolve it effectively, but I'm sure the above suggestions will not resolve the issues.
Does someone have the ping-timeout
on the client-side with long sessions**? @danielmapar can help with your experience around this?
** Sessions up to 12 hours.
EDIT: 30% of the time we can handle sessions with a duration of 5-6 hours without problems.
I made full web chat app with nodejs && socket.io,everything works perfect(public messages ,private messages),but i have a big issue when user comes from android mobile to my chat,connection somehow cant be alive and after 2 years i still havent answer why,does that happens because of android sleep mode or or or? Any suggestions friends?
Is Socket.IO not the right library to use if connections must be kept alive or recovered?
I'm also having issues with users being disconnected after just a couple of minutes, sometimes less than a minute. This is frustrating because in my application, users go through steps together so if someone loses their socket then progress is lost and they must start over.
Of course reloading the page will also disconnect and reconnect. Unfortunately too though, socket.id
is read-only so previous uuid
s (and single user rooms) cannot be easily restored. In the case of private chat rooms with 2 or more users, if someone gets dropped and reconnects with a new uuid
, the server should be able to add them back to the room(s) they were in but will need to know exactly which rooms. I think this is where cookies will be helpful. However if anyone knows of a better approach, please chime in.
What feature keeps this from being fixed? or what benefit is it to disconnect? Heroku terminates 'idle' connections, but a websocket ping fixes that and websockets themselves don't just close.
I found debug options, and enabled DEBUG=* on both sides. I see the server sends engine:ws writing "0{"sid":"DmzJW2TrCNP7kuWcAAAA","upgrades":[],"pingInterval":25000,"pingTimeout":60000}"
which, the connection closes 25 seconds after start. Seems like someone misunderstood something at some point... there is no ping sent; which I would presume should be controlled by pingInterval
, instead the connection is closed at that point. Probably the pingTimeout
at 60 seconds should fire if a ping was sent and not responded to - but, again, there is no ping sent; just a close at interval.
Aug 13 15:22:18 hostname node[15956]: 2022-08-13T15:22:18.049Z - info: SocketIO > Connected socket C3hJWXpJQ1ssv7EOAAAL
Aug 13 15:22:18 hostname node[15956]: Sat, 13 Aug 2022 15:22:18 GMT socket.io:socket joined room C3hJWXpJQ1ssv7EOAAAL
Aug 13 15:23:43 hostname node[15956]: Sat, 13 Aug 2022 15:23:43 GMT engine:ws closing
Would love to know if this is going to be addressed.
@Apezdr there are a lot of information in this thread, do you have a particular suggestion?
Connection on mobile browser should remain active.
Here's a suggestion regarding reconnection , feel free to chime in :+1:
Else, I think WebSocket over mobile connections will always be a little shaky, I'm not sure how we could fix this in the library. Should we delay the disconnection? (ie. the disconnect
event is sent after X seconds, if the socket has not reconnected yet)
I think the problem is not socket.io it's the hosting. I have this problem on Railway.app but when I run the server on my local machine localhost I do not have this issue. Something with proxy
For now my workaround is to keep a record of all connects and message on the server. use the reconnect listener on the clients and have it to fetch the messages or data from the server on reconnect. Very messy but works.
This happens regardless of hosting. Yes there are hosts that disconnect idle connections too - which is why ping needs to work; setting it to 24 hour timeout isn't a good solution either. It's baked right into the code to generate a disconnect on the first ping timeout; and there's apparently no option except to timeout since the client never handles the ping?
@d3x0r do you have a way to prevent this from happening I am really struggling with this. This happens to me even with me sending traffic. I send a new emit every 10 seconds but still disconnect and reconnect every 5 to 10 minutes.
@d3x0r do you have a way to prevent this from happening I am really struggling with this. This happens to me even with me sending traffic. I send a new emit every 10 seconds but still disconnect and reconnect every 5 to 10 minutes.
In my case, I'm on a LAN, and don't have to worry about idle disconnects, so I can set on the server options
pingInterval:24*60*60*1000,
pingTimeout:3*24*60*60*1000
which the doesn' t disconnect for a day. I'm more interested in quiet disconnects ( where clients/servers disconnect without actually saying anything) so a manual ping type event on both sides can help.
@d3x0r I tried to set pingInterval and pingTimeout however I have the same issue. Disconnect every 10 minutes
import express from 'express';
import http from 'http';
import { Server } from 'socket.io';
import cors from 'cors';
import { roomHandler } from './room/index.js';
const app = express();
app.use(cors);
const port = process.env.PORT || 9723;
const server = http.createServer(app);
export const io = new Server(server, {
pingInterval: 24 * 60 * 60 * 1000,
pingTimeout: 3 * 24 * 60 * 60 * 1000,
cors: {
origin: '*',
methods: ['GET', 'POST']
}
});
io.on('connection', (socket) => {
console.log('a user connected');
roomHandler(socket);
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
server.listen(port, () => {
console.log(`listening on *:${port}`);
});
@elmcremotebridge then enabling debug on the client and server might help to at least know which side is doing the disconnect first? and maybe a related reason for the close? With it set that way it won't be the ping timeout; might still be a provider thing; maybe a maximum time to live of a process; but then you wouldn't get the disconnect event there either.. https://socket.io/docs/v4/logging-and-debugging/
I am using Railway.io hosting. Their support message me. Yes, when you proxy requests at Railway scale, keep alive connections have to be killed. You need to send some keepalive traffic on your websocket every 10-30 secs (socketio does this with websocket pings by default) so that you don't hit any TCP idle timeouts.
I have all. of my client's emit a message every 10 seconds using setInterval but still disconnects after 10 minutes then reconnect. I don't have this issue when I am running the server on my localhost computer
We are experiencing same issues with some of our socket connections and could do with some clear guidance as to what we need to check as I’m running out of ideas? We are using v2.4.x
Struggling with sockets for almost an year, we decided to migrate to pub/sub architecture. We are engineering an enterprise application and could not afford such issues with our application. To overcome such issues, the pub/sub is a better alternative. There are many pub/sub API providers. You may go with anyone. Also there are many other socket API providers with paid services. You may try those.
Having the same issue here on a simple single page application. Using Railway.app for hosting and chrome for the browser.
It seems that each user is disconnected 10 mins after they join. Meaning, if 3 users join in a specific order, they will be disconnected in that exact same order. User activity does not seem to have any effect.
Socket.io disconnect reason for each user is transport close
: The connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)
I have not adjusted any pingtimeout
or pinginterval
settings.
Versions: socket.io-client: 4.5.4 socket.io: 4.5.4
(EDIT 1: Just tried using Firefox and the same thing is happening). (EDIT 2: Just tried replicating on localhost and no user was disconnected after 15 mins) (EDIT 3: Tried out "Render.com" for free hosting. Unlike Railway.app, every user consistently disconnected after 5 mins)