'iPhone can't seem to keep connection to server using socket.io
I'm creating a browser-based app using node.js and socket.io. It allows users to create a game, and join a room using a room code (sort of like Jackbox Games, if you've seen that). Here's the problem I'm having. On my laptop, the connection stays open, but if I connect with my phone, the connection randomly closes. I've confirmed this as follows:
On the client side, I have this code:
const socket = io();
socket.on('ping', (data) => {
showMessage('info', 'ping', 500);
socket.emit('pong', data);
});
socket.on('error', (data) => {
showMessage('error', data.message, 2000);
});
We initialize the socket, and then just immediately emit a 'pong' whenever the server sends us a 'ping'. ShowMessage is a function that flashes a message on screen - here's it's merely diagnostic.
On the server side, I have:
const socket = (http, server) => {
const io = require('socket.io')(http, {
pingInterval: 1000,
pingTimeout: 1000,
});
io.listen(server);
setInterval(() => {
pingTime = Date.now();
io.emit('ping', null);
}, pingInterval);
io.on('connection', (socket) => {
console.log(`A user has connected from ${socket.handshake.address}`);
console.log(`\tID: ${socket.id}`);
}
}
Here's the problem. On my computer, I can go to localhost:3000 and see the "ping" message blinking on the screen. It keeps going until I kill the server. When I do it on my iPhone 11 (using Chrome), the "ping" message blinks for a bit, and then stops, presumably as the socket is closed. The pingInterval and pingTimeout settings on the server side mean that the socket will reconnect pretty quickly. Unfortunately, as the app I'm trying to build is a buzzer for a speed-based game (think Jeopardy - first person to hit the button gets to answer the question), just reconnecting alone isn't good enough - I would really prefer it if the socket would stay open. Is there a way to force it to stay open?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
