Socket.io 发送带有参数的断开连接事件 [英] Socket.io send disconnect event with parameter
问题描述
我想手动发送带有自定义参数的断开连接事件到 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?
推荐答案
Socket 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屋!