How to destroy RTCPeerConnection?

Viewed 7280

I can use the following code to create a new peer connection object:

var peer = new RTCPeerConnection();

When this happens, chrome shows it as new connection object in chrome://webrtc-internals/

I would like to destroy this object later. How to do it? I tried

peer.close();

but this does not seem to do anything, since the peer variable is still of type RTCPeerConnection and I can still see it active in chrome://webrtc-internals/.

If I unset the variable, like

peer=false;

it still shows it in chrome://webrtc-internals/. Yet if I close the webpage then it immediately disappears from chrome://webrtc-internals/.

What is the proper way to free the RTCPeerConnection object? I am asking because if I do not free them, I am occasionally getting refusal from web browser to create new RTCPeerConnection because there are too many of them in use.

2 Answers

on which event you want to destroy it ? there maybe a missing part within your code that leave the connection opened here is a whole PDF book explaining how WebRtc Works on browsers ,

click here to download it

i am giving this book to you so you can check if there is any parts of your code that leave the connection open some where on this case even if you closed the peer on that specific event it will still show up and remains on the browser .

As for your question ,assuming that you want to close it from a button click lets call it Hang Up button , //hang up

hangUpBtn.addEventListener("click", function () { 

send({ 
  type: "leave" 
});

handleLeave(); 
});

function handleLeave() { 
connectedUser = null; 
remoteVideo.src = null; 

yourConn.close(); 
yourConn.onicecandidate = null; 
yourConn.onaddstream = null; 
};

When the user disconnects you should clean up its connection. you can delete the user when the close event is fired. Add the following code to the connection handler

connection.on("close", function() { 
if(connection.name) { 
 delete users[connection.name]; 
} 
});

when the user click on hang button It will send a “leave” message to the other user It will close the RTCPeerConnection and destroy the connection locally

this should close the rtc connection , as far as i remember there is bug on chrome even if you closed the connection it will make leak on the memory not sure if this bug still there .

one more thing when user exits, for example closes a browser window this may help if we are still in "offer","answer" or "candidate" state

  connection.on("close", function() { 

  if(connection.name) { 
  delete users[connection.name]; 

  if(connection.otherName) { 
  console.log("Disconnecting from ", connection.otherName); 
  var conn = users[connection.otherName]; 
  conn.otherName = null;  

  if(conn != null) { 
  sendTo(conn, { 
  type: "leave" 
  }); 
  }  
  } 
  } 
  });  

  connection.send("Hello world"); 
  }); 
Related