gpt4 book ai didi

node.js - Nodejs + ReactJS socket.io off/removeListener 不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:44 26 4
gpt4 key购买 nike

我正在尝试在我的react/nodejs应用程序上实现socket.io。我可以成功订阅一个事件并将数据推送到前端。但当不再需要某个事件时,我无法取消订阅该事件。

版本套接字.io - 2.0.4socket.io-client - 2.0.4

下面是示例代码

前端

subscribeForTimer() {
socket.on('timer', timestamp => {
console.log(timestamp)
});
socket.emit('subscribeToTimer', 1000);
}

UnubscribeFromTimer() {
socket.removeListener ( 'timer', (data) => {
console.log ( 'stopped' )
} );
}

后端

const socketServer = http.createServer ();
// create a server instance with the port and host
socketServer.listen ( port, host );

// Make the sockets listen on the created server instance
const sio = io.listen ( socketServer );
sio.sockets.on ( socketEvents.CONNECTION, ( socket ) => {
subscribeToTimer ( socket );
UnubscribeFromTimer ( socket );
terminateConnection ( socket );
} );
function subscribeToTimer ( socket ) {
socket.on ( 'subscribeToTimer', ( interval ) => {
setInterval ( () => {
socket.emit ( 'timer', new Date () );
}, interval );
} );
}

我尝试过使用 off/removeListener/removeAllListeners 但没有任何效果。它也不会抛出任何错误。任何帮助深表感谢。 TIA!

最佳答案

您应该传递订阅函数的相同实例来取消订阅:

在前端:

const subscribeFn = timestamp => {
console.log(timestamp)
}

subscribeForTimer() {
socket.on('timer', subscribeFn);
socket.emit('subscribeToTimer', 1000);
}

UnubscribeFromTimer() {
socket.removeListener('timer', subscribeFn);
}

在后端

const socketServer = http.createServer ();
// create a server instance with the port and host
socketServer.listen ( port, host );

// Make the sockets listen on the created server instance
const sio = io.listen ( socketServer );
let intervalId;
sio.sockets.on ( socketEvents.CONNECTION, ( socket ) => {
subscribeToTimer ( socket );
intervalId && clearInterval(intervalId)
UnubscribeFromTimer ( socket );
terminateConnection ( socket );
} );
function subscribeToTimer ( socket ) {
socket.on ( 'subscribeToTimer', ( interval ) => {
intervalId = setInterval ( () => {
socket.emit ( 'timer', new Date () );
}, interval );
} );
}

关于node.js - Nodejs + ReactJS socket.io off/removeListener 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48883096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com