D
D
dfhkjhg2020-09-13 23:42:28
Express.js
dfhkjhg, 2020-09-13 23:42:28

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)))
    })
})


But for some reason, instead of one message, the user receives several identical

5f5e8401caac5785435720.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2020-09-13
@dfhkjhg

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)

solution (before watching, try to find a solution yourself)
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 question

Ask a Question

731 491 924 answers to any question