我试图在我的react / nodejs应用上实现socket.io。我可以成功订阅一个事件并将数据推送到前端。但是,当不再需要时,我无法取消订阅。
版本 socket.io - 2.0.4 socket.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!
答案 0 :(得分:2)
您应该将订阅函数的相同实例传递给unsubscribe:
在前端:
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 );
} );
}