Reputation: 279
When I make changes to my Node/Socket IO server and restart it, the connected client will start emitting two messages for each one. If I restart again, it will start emitting three, and so forth.
The only "fix" I see is to refresh the page on client to force a new connection.
How do I prevent the client from emitting multiple messages after a server restart?
Pretty standard setup:
Server
const app = express();
const port = process.env.PORT || 4000;
const server = app.listen(port, () => l(`Server started on port ${port}`));
const io = require('socket.io').listen(server);
app.get('/', (req, res) => {
res.sendFile('/public/index.html', { root: __dirname });
});
io.on('connection', client => client.on('event', (msg) => console.log(msg));
Client
const socket = io.connect('', { query: { path: window.location.pathname }, reconnect: false, forceNew: true });
$("body").on("click", "a", () => socket.emit('event', 'test'));
Upvotes: 0
Views: 1322
Reputation: 653
Here is the solution: https://github.com/socketio/socket.io/issues/430#issuecomment-451130988
Don't wrap the socket.on in actions like connect or authenticated.
In my example I had a "socket.on" wrapped in authorization. As soon as the client reconnected the socket.on stacked up and multiplied each time the server restarted.
Upvotes: 2