Socket.io发送带有参数的断开连接事件 [英] Socket.io send disconnect event with parameter

查看:635
本文介绍了Socket.io发送带有参数的断开连接事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自定义参数手动将断开连接事件发送到socket.io服务器.我使用了此功能,但无法使用:

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

//客户端

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

//服务器

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

现在发送断开事件后如何向服务器发送其他数据?

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

推荐答案

套接字IO的断开事件是在内部触发的,但是在调用它时可以发出自定义事件.

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

您需要先监听断开连接事件.调用此事件后,您应发出自己的自定义事件,说我们将其称为myCustomEvent.调用此事件后,您的客户端应侦听您的myCustomEvent,并在听到该消息后,应输出您传递的数据.例如:

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

您的客户然后会像这样监听myCustomEvent

Your client would then listen for myCustomEvent like so

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

我希望这会有所帮助:)

I hope this helps :)

这篇关于Socket.io发送带有参数的断开连接事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆