Answer the question
In order to leave comments, you need to log in
Why does websocket send multiple identical messages to the same user?
Here is the route where I call emit
app.js
req.app.emit('broadcast', data)
ws.on('connection', (socket) => {
console.log('connected')
app.on('broadcast', (data = {}) => {
ws.clients.forEach(client => client.send(JSON.stringify(data)))
})
})
Answer the question
In order to leave comments, you need to log in
Apparently because every time any client connects, you hang a new handler on the broadcast event, which sends information to all connected clients.
As a result, it turns out like this:
1. Restarted the server, thereby resetting all connections
2. Entered the site (or refreshed the page) -> connection happened -> the 'connection' event worked -> the handler for the 'broadcast' event was hung up
3. Re-entered the site (or refreshed the page) -> connection happened -> 'connection' event fired -> one more handler was hung on the 'broadcast' event
4. guess how many messages the client will now receive when calling ?req.app.emit('broadcast', data)
ws.on('connection', (socket) => {
console.log('connected')
})
app.on('broadcast', (data = {}) => {
ws.clients.forEach(client => client.send(JSON.stringify(data)))
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question