前置背景:
一段創(chuàng)建socket連接的代碼
conncet(xxxxx){
this.socket = net.createConnection({ host: ip, port: port }, () => {
console.log(this.socket);
if(this.socket){
this.socket.on("data", xxxxx)
}
}
this.socket.on('close', () => {
this.socket = null;
});
}
在創(chuàng)建之前會先關(guān)閉之前的連接
// 斷開連接
close() {
this.socket?.destroy();
this.socket = null;
}
業(yè)務(wù)功能上有個登錄的按鈕,可以反復(fù)登錄,然后第二次登錄時發(fā)現(xiàn)創(chuàng)建時的socket回調(diào)里獲取到的this.socket為null
image.png
原因:
this.socket.destroy是同步的,但是銷毀后會觸發(fā)上面手動綁定的close事件,這個事件觸發(fā)是異步的,然而這個onClose的回調(diào)里的代碼是將 this.socket置為null,剛好在下一次創(chuàng)建連接后,回調(diào)之前觸發(fā)了,所以導(dǎo)致獲取不到 this.socket
解決:
這里的socket = null去掉即可
this.socket.on('close', () => {
// this.socket = null;
});