nodejs net模塊長連接close問題

前置背景:

一段創(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;
  });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容