Socket.io send disconnect event with parameter

喜欢而已 提交于 2019-12-22 09:48:41

问题


I want to send disconnect event manually with custom parameter to socket.io server. I use this function but won't work:

//client

var userId = 23;
socket.disconnect(user);

//Server

socket.on('disconnect', function (data) {
        console.log('DISCONNECT: '+  data)
    })

Now how can I send a additional data to server when disconnect event sent?


回答1:


Socket IO's disconnect event is fired internally but you can emit a custom event when it is called.

You need to first listen for the disconnect event. Once this event has been called, you should then emit your own custom event say we call it myCustomEvent Once this event has been called, your client should then be listening out for your myCustomEvent and on hearing it, should then output the data you passed it. For example:

io.sockets.on('connection', function (socket) {
  const _id = socket.id
  console.log('Socket Connected: ' + _id)
  // Here we emit our custom event
  socket.on('disconnect', () => {
    io.emit('myCustomEvent', {customEvent: 'Custom Message'})
    console.log('Socket disconnected: ' + _id)
  })
})

Your client would then listen for myCustomEvent like so

socket.on('myCustomEvent', (data) => {
    console.log(data)
})

I hope this helps :)



来源:https://stackoverflow.com/questions/40816355/socket-io-send-disconnect-event-with-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!