You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中关闭RTCPeerConnection时如何清理遗留Unix域套接字?

问题与解决方案

现象

调用peerConnection.close()关闭WebRTC连接后,关联的Unix域套接字未自动销毁,每次新建RTCPeerConnection都会导致套接字数量持续累积,进程日志显示大量处于CONNECTED状态的Unix套接字:

unix  3      [ ]         STREAM     CONNECTED     3410597  14738/Liveview       
unix  3      [ ]         STREAM     CONNECTED     3417284  14738/Liveview       
unix  3      [ ]         STREAM     CONNECTED     3417285  14738/Liveview       
unix  3      [ ]         STREAM     CONNECTED     3410598  14738/Liveview       
unix  3      [ ]         STREAM     CONNECTED     3405499  14738/Liveview       
unix  3      [ ]         STREAM     CONNECTED     3410595  14738/Liveview       
unix  3      [ ]         STREAM     CONNECTED     3405497  14738/Liveview       
unix  3      [ ]         STREAM     CONNECTED     3410594  14738/Liveview  

相关代码

初始化连接:

const { RTCPeerConnection } = require('wrtc')

this.peerConnection = new RTCPeerConnection(this.rtcConfig)

关闭连接代码:

this.peerConnection.close();

解决方法

  • 显式清除连接引用
    调用close()后,手动将peerConnection置为null,让JS垃圾回收器能回收关联资源:
this.peerConnection.close();
this.peerConnection = null;
  • 提前清理媒体轨道
    在关闭连接前,移除所有发送/接收轨道并停止媒体流,避免轨道持有套接字引用:
// 移除所有发送轨道
this.peerConnection.getSenders().forEach(sender => {
  this.peerConnection.removeTrack(sender);
});
// 停止并清理接收轨道
this.peerConnection.getReceivers().forEach(receiver => {
  receiver.track?.stop();
});
// 关闭连接并清除引用
this.peerConnection.close();
this.peerConnection = null;
  • 升级wrtc库版本
    部分旧版本的wrtc存在资源泄漏Bug,升级到最新稳定版可解决这类问题:
npm install wrtc@latest
  • 监听连接状态完成清理
    通过connectionstatechange事件监听连接状态,确保在连接彻底关闭后清理资源:
this.peerConnection.addEventListener('connectionstatechange', () => {
  if (this.peerConnection.connectionState === 'closed') {
    this.peerConnection = null;
  }
});

内容的提问来源于stack exchange,提问作者uttam chaudhary white elephant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:55:15