Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

call.on("close") not triggered #636

Closed
alfonsograziano opened this issue Mar 24, 2020 · 43 comments · Fixed by #963
Closed

call.on("close") not triggered #636

alfonsograziano opened this issue Mar 24, 2020 · 43 comments · Fixed by #963

Comments

@alfonsograziano
Copy link

Hi, i have a p2p connection and when i do call.close(), on("close",...) is triggered only on the peer that calls che close function. How can i trigger both the peers? Thank's!

@protyze
Copy link

protyze commented Apr 12, 2020

I can confirm the report of @LOKK3D. I have the same issue.

Description
Unexpected behaviour when closing a MedieConnection between two peers.

Steps to reproduce

  1. Establish a MediaConnection between 2 peers
  2. Execute "call.close()" on peer 1.
  3. Listen to "close" and "error" events on peer 2.
  4. Observe which events are triggered on peer 2 after step 2.

Expected Result
Peer 2 should receive a "close" event after peer 1 closed the call. An error event should not be fired.

Actual Result
Peer 2 received an "error" event: "Error: Connection to disconnected."

Is this intentional?

@cliqer
Copy link

cliqer commented Dec 15, 2020

So, how do we close the call?
MediaConnection.close does never gets fired.
Is this a bug? Any workarounds?

@MoradAbdelgaber
Copy link

same problem here . Listen to "close" and "error" events on peer 2. nothing happened if peer 1 close call !!

@cliqer
Copy link

cliqer commented Dec 23, 2020

@MoradAbdelgaber, just send a signal to destroy the peer through WebSocket.
No other way around it.

@AlvaroHerrero
Copy link

Same problem here

@albertogcatalan
Copy link

Same here!

@mactunechy
Copy link

And same here

@xtrars
Copy link

xtrars commented Feb 15, 2021

and same here

@mactunechy
Copy link

I found a way that worked for me, I'm using peerjs alongside socket.io, so when i kill the call by peer.close(), I then emit an event "close" via socket.io and the other peer will subscribe to that event with socket.on("close",()=>{})

@amanKumar689
Copy link

same problem here . Listen to "close" and "error" events on peer 2. nothing happened if peer 1 close call !!

yeah bro me same problem i think its a bug

@sbehrends
Copy link

I am seeing same unexpected behavior where call.on('close', () => {}) is not being called when call is dropped.
If it is useful I can provide some kind of Codepen or similar to replicate the issue

@YoussF
Copy link

YoussF commented Feb 28, 2021

Same issue here :)

@azlogs
Copy link

azlogs commented Mar 7, 2021

I have a workaround solution that I answered in stackoverflow
https://stackoverflow.com/questions/64651890/peerjs-close-video-call-not-firing-close-event/66518772#66518772

@rkhaslarov
Copy link

same issue...

@naonvl
Copy link

naonvl commented Apr 28, 2021

I have a workaround solution that I answered in stackoverflow
https://stackoverflow.com/questions/64651890/peerjs-close-video-call-not-firing-close-event/66518772#66518772

is there any workaround without websocket?

@chadwallacehart
Copy link

I use the public peerjs server. I was able to manually close the peerConnections by getting them from peer.connections. I noticed that the dataConnection close event still fires, so I wait for this and then close all open peerConnections:

function handlePeerDisconnect() {
  // manually close the peer connections
  for (let conns in peer.connections) {
    peer.connections[conns].forEach((conn, index, array) => {
      console.log(`closing ${conn.connectionId} peerConnection (${index + 1}/${array.length})`, conn.peerConnection);
      conn.peerConnection.close();

      // close it using peerjs methods
      if (conn.close)
        conn.close();
    });
  }
}

peer.on('connection', conn => {
    let call = peer.call(peerToCall, localStream);
   
    // peerjs bug prevents this from firing: https://github.com/peers/peerjs/issues/636
    call.on('close', () => {
        console.log("call close event");
        handlePeerDisconnect();
    });
}

    // this one works
    conn.on('close', () => {
        console.log("conn close event");
        handlePeerDisconnect();
    });
});

I also responded here: https://stackoverflow.com/questions/64651890/peerjs-close-video-call-not-firing-close-event/67404616#67404616

chadwallacehart added a commit to cogint/webwebcam that referenced this issue May 6, 2021
@wilsonfurtado2000
Copy link

I use the public peerjs server. I was able to manually close the peerConnections by getting them from peer.connections. I noticed that the dataConnection close event still fires, so I wait for this and then close all open peerConnections:

function handlePeerDisconnect() {
  // manually close the peer connections
  for (let conns in peer.connections) {
    peer.connections[conns].forEach((conn, index, array) => {
      console.log(`closing ${conn.connectionId} peerConnection (${index + 1}/${array.length})`, conn.peerConnection);
      conn.peerConnection.close();

      // close it using peerjs methods
      if (conn.close)
        conn.close();
    });
  }
}

peer.on('connection', conn => {
    let call = peer.call(peerToCall, localStream);
   
    // peerjs bug prevents this from firing: https://github.com/peers/peerjs/issues/636
    call.on('close', () => {
        console.log("call close event");
        handlePeerDisconnect();
    });
}

    // this one works
    conn.on('close', () => {
        console.log("conn close event");
        handlePeerDisconnect();
    });
});

I also responded here: https://stackoverflow.com/questions/64651890/peerjs-close-video-call-not-firing-close-event/67404616#67404616

what is the conn variable here ??
could you help me i am facing the same

@rodrigomarcell
Copy link

I use the public peerjs server. I was able to manually close the peerConnections by getting them from peer.connections. I noticed that the dataConnection close event still fires, so I wait for this and then close all open peerConnections:

function handlePeerDisconnect() {
  // manually close the peer connections
  for (let conns in peer.connections) {
    peer.connections[conns].forEach((conn, index, array) => {
      console.log(`closing ${conn.connectionId} peerConnection (${index + 1}/${array.length})`, conn.peerConnection);
      conn.peerConnection.close();

      // close it using peerjs methods
      if (conn.close)
        conn.close();
    });
  }
}

peer.on('connection', conn => {
    let call = peer.call(peerToCall, localStream);
   
    // peerjs bug prevents this from firing: https://github.com/peers/peerjs/issues/636
    call.on('close', () => {
        console.log("call close event");
        handlePeerDisconnect();
    });
}

    // this one works
    conn.on('close', () => {
        console.log("conn close event");
        handlePeerDisconnect();
    });
});

I also responded here: https://stackoverflow.com/questions/64651890/peerjs-close-video-call-not-firing-close-event/67404616#67404616

yeah but where you are getting the peer id from to close the current disconnected peer call?

@chadwallacehart
Copy link

@wilsonfurtado2000 - when you create a peer with new Peer(someId), the peer object keeps an array of all the connections you make. If I recall correctly, the connections are stored in some kind of generator object. You cann grab each of them individually - that is what the conn variable is in the handlePeerDisconnect function above. I had to do some inspectionn to find these.

@rodrigomarcell - in tht example I am closing every connection associted with the given peer. You should be able to close specific peers by ID with something like the below:

    function manualClose(TARGET_ID) {
        // close the peer connections
        for (let conns in peer.connections) {
            peer.connections[conns].forEach((conn, index, array) => {

                // Manually close the peerConnections b/c peerJs MediaConnect close not called bug: https://github.com/peers/peerjs/issues/636
                if (conn.peer === TARGET_ID) {
                    console.log(`closing ${conn.connectionId} peerConnection (${index + 1}/${array.length})`, conn.peerConnection);
                    conn.peerConnection.close();

                    // close it using peerjs methods
                    if (conn.close) {
                        conn.close();
                    }
                }
            });
        }
    }

@MaxPao
Copy link

MaxPao commented Aug 7, 2021

Maybe I confuse this issue.
but I face this same problem, and I resolve it.

my project has 2 block script , one is [connect to], one is [listen connect]
if in those 2 way you set 'close' event .
then it can fired when other side to close event.

when I get this issue, I only write one side 'close' event....

@matallui
Copy link
Contributor

Just encountered this same issue. Any progress on this?

@rodrigomarcell
Copy link

Just encountered this same issue. Any progress on this?

I guess the messages above may help you.

@matallui
Copy link
Contributor

I understand there's workarounds for this. But any updates on whether this is going to be fixed? Looks like this issue has been open since 2020.

@matallui
Copy link
Contributor

matallui commented Apr 29, 2022

Not sure what the real fix for this will be, but I managed to get this working with this patch.

If you want to give it a try you should be able to install my patched version of peerjs:

npm i matallui/peerjs#fix_mediastream_close

The solution involved creating a RTCDataChannel for each MediaConnection, similar to what is done to the DataConnection. I still would love to figure out a cleaner way of doing that, but at least this is working for now.

@JoleMile
Copy link

JoleMile commented May 2, 2022

Not sure what the real fix for this will be, but I managed to get this working with this patch.

If you want to give it a try you should be able to install my patched version of peerjs:

npm i matallui/peerjs#fix_mediastream_close

The solution involved creating a RTCDataChannel for each MediaConnection, similar to what is done to the DataConnection. I still would love to figure out a cleaner way of doing that, but at least this is working for now.

Not sure how this is working, but it seems to be working great. Thank you :)

@AllanPinheiroDeLima
Copy link

Not sure what the real fix for this will be, but I managed to get this working with this patch.

If you want to give it a try you should be able to install my patched version of peerjs:

npm i matallui/peerjs#fix_mediastream_close

The solution involved creating a RTCDataChannel for each MediaConnection, similar to what is done to the DataConnection. I still would love to figure out a cleaner way of doing that, but at least this is working for now.

I was about to make this myself. Why don't you open a pull request for them ? Your solution works great!
Thank you!

@matallui
Copy link
Contributor

@AllanPinheiroDeLima I was just trying to make sure this is the correct solution. I assume at some point the remote close() functionality was working, so would like to understand why it stopped working. I was hoping to figure out a better way without having to create that extra channel. But I guess I can open a PR and go from there.

jonasgloning added a commit that referenced this issue May 25, 2022
@matallui
Copy link
Contributor

matallui commented May 25, 2022

@jonasgloning just tested this and have a couple of comments:

1- this (kind of) fixes the issue but it's not good enough in my case... it's only disconnecting when we get the ICE disconnect event, which takes a few seconds after I actually stop the MediaConnection on the sharing side. With the extra DataChannel at least we get an instant disconnect as soon as one side calls MediaConnection.close(), which is the behavior I'd expect according to the docs.

2- I'm getting a TS build error now saying the MediaConnection.answer() requires a mandatory stream argument. Not sure at what point things have changed, but this used to be an optional argument and we could still answer calls without sharing a stream back. Any ideas what happened with that?

@matallui
Copy link
Contributor

This commit seems to be where index.d.ts got removed and the interface for MediaConnection.answer() changed.

jonasgloning pushed a commit that referenced this issue May 25, 2022
## [1.4.6-rc.1](v1.4.5...v1.4.6-rc.1) (2022-05-25)

### Bug Fixes

* `close` event was not triggered reliably ([#860](#860)) ([ec1d5ae](ec1d5ae)), closes [#636](#636)

### Performance Improvements

* **turn:** reduce turn server count ([8816f54](8816f54))
@peers peers deleted a comment from github-actions bot May 25, 2022
@jonasgloning
Copy link
Member

Thanks for testing, @matallui!

1- this (kind of) fixes the issue but it's not good enough in my case... it's only disconnecting when we get the ICE disconnect event, which takes a few seconds after I actually stop the MediaConnection on the sharing side. With the extra DataChannel at least we get an instant disconnect as soon as one side calls MediaConnection.close(), which is the behavior I'd expect according to the docs.

You’re right, the delay is to large. So this isn’t a complete solution. Unfortunately, I won’t have the time to look into it the next few weeks. But I would merge a PR with your solution, at least in rc for further testing.

2- I'm getting a TS build error now saying the MediaConnection.answer() requires a mandatory stream argument. Not sure at what point things have changed, but this used to be an optional argument and we could still answer calls without sharing a stream back. Any ideas what happened with that?

There were some inconsistencies with the handwritten types, so I switched to autogenerating them in your linked commit. Turns out the types in the source weren’t accurate either. Fixed in 666dcd9, more type improvements 2b53de2.

@matallui
Copy link
Contributor

@jonasgloning thanks for the prompt response and for fixing 2). I will submit a PR soon with my fixes for 1) so we can test it in RC and we'll go from there.

@matallui
Copy link
Contributor

@jonasgloning PR submitted. Thanks again for all the help!

@alibawazeer611
Copy link

when i calling video the peer close by self why this happend'

github-actions bot pushed a commit that referenced this issue Feb 25, 2023
## [1.4.8-rc.1](v1.4.7...v1.4.8-rc.1) (2023-02-25)

### Bug Fixes

* `close` event was not triggered reliably ([#860](#860)) ([ec1d5ae](ec1d5ae)), closes [#636](#636)
* **datachannel:** sending order is now preserved correctly ([18d491a](18d491a)), closes [#746](#746)
* **deps:** update dependency @swc/helpers to ^0.4.0 ([a7de8b7](a7de8b7))
* **deps:** update dependency eventemitter3 to v5 ([caf01c6](caf01c6))
* **deps:** update dependency webrtc-adapter to v8 ([431f00b](431f00b))
* **npm audit:** Updates all dependencies that cause npm audit to issue a warning ([6ef5707](6ef5707))
@peers peers deleted a comment from github-actions bot Feb 25, 2023
@bioshazard
Copy link

Hello from 2023, I can't seem to get any on event to trigger when closing one of the peer tabs ungracefully.

@neilyoung
Copy link

Maybe I confuse this issue. but I face this same problem, and I resolve it.

my project has 2 block script , one is [connect to], one is [listen connect] if in those 2 way you set 'close' event . then it can fired when other side to close event.

when I get this issue, I only write one side 'close' event....

What?

@dugiwarc
Copy link

dugiwarc commented May 13, 2023

Yes, this still seems to be an issue, none of the 'on' events gets triggered. Only solution is to use web sockets for now.

@hayelom123
Copy link

Is it fixed?,or should I use just the webrtc

@neilyoung
Copy link

Is it fixed?,or should I use just the webrtc

I recommend https://github.com/feross/simple-peer

It's less buggy

@briannydegger
Copy link

briannydegger commented Jun 21, 2023

I personally use something like:

this.conn = this.peer.call(this.anotherid, stream);

this.conn.on('iceStateChanged', (state) => {
    if (state === 'disconnected') {
        this.endCall();
    }
});

Just have to wait few seconds to have the result.

Best regards

jonasgloning pushed a commit that referenced this issue Jun 22, 2023
### Problem

`MediaConnection.close()` doesn't propagate the `close` event to the
remote peer.

### Solution

The proposed solution uses a similar approach to the `DataConnection`,
where an aux data channel is created for the connection.
This way, when we `MediaConnection.close()` the data channel will be
closed and the `close` signal will be propagated to the remote peer.

#### Notes

I was not sure if there was another cleaner way of achieving this,
without the extra data channel, but this seems to work pretty well (at
least until a better solution comes up).

This should fix: #636

---------

Co-authored-by: Jonas Gloning <[email protected]>

Closes #636, Closes #1089, Closes #1032, Closes #832, Closes #780, Closes #653
jonasgloning added a commit that referenced this issue Jun 22, 2023
github-actions bot pushed a commit that referenced this issue Aug 14, 2023
# [1.5.0-rc.1](v1.4.8-rc.1...v1.5.0-rc.1) (2023-08-14)

### Bug Fixes

* **datachannel:** sending order is now preserved correctly ([#1038](#1038)) ([0fb6179](0fb6179)), closes [#746](#746)
* **deps:** update dependency peerjs-js-binarypack to v1.0.2 ([7452e75](7452e75))
* **deps:** update dependency webrtc-adapter to v8.2.2 ([62402fc](62402fc))
* **deps:** update dependency webrtc-adapter to v8.2.3 ([963455e](963455e))
* **MediaConnection:** `close` event is fired on remote Peer ([0836356](0836356)), closes [#636](#636) [#1089](#1089) [#1032](#1032) [#832](#832) [#780](#780) [#653](#653)

### Features

* **DataConnection:** handle close messages and flush option ([6ca38d3](6ca38d3)), closes [#982](#982)
* **MediaChannel:** Add experimental `willCloseOnRemote` event to MediaConnection. ([ed84829](ed84829))
* MsgPack/Cbor serialization ([fcffbf2](fcffbf2))
@github-actions
Copy link

🎉 This issue has been resolved in version 1.5.0-rc.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

@hayelom123
Copy link

hayelom123 commented Aug 14, 2023 via email

github-actions bot pushed a commit that referenced this issue Sep 3, 2023
# [1.5.0](v1.4.7...v1.5.0) (2023-09-03)

### Bug Fixes

* **datachannel:** sending order is now preserved correctly ([#1038](#1038)) ([0fb6179](0fb6179)), closes [#746](#746)
* **deps:** update dependency @swc/helpers to ^0.4.0 ([a7de8b7](a7de8b7))
* **deps:** update dependency cbor-x to v1.5.4 ([c1f04ec](c1f04ec))
* **deps:** update dependency eventemitter3 to v5 ([caf01c6](caf01c6))
* **deps:** update dependency peerjs-js-binarypack to v1.0.2 ([7452e75](7452e75))
* **deps:** update dependency webrtc-adapter to v8 ([431f00b](431f00b))
* **deps:** update dependency webrtc-adapter to v8.2.2 ([62402fc](62402fc))
* **deps:** update dependency webrtc-adapter to v8.2.3 ([963455e](963455e))
* **MediaConnection:** `close` event is fired on remote Peer ([0836356](0836356)), closes [#636](#636) [#1089](#1089) [#1032](#1032) [#832](#832) [#780](#780) [#653](#653)
* **npm audit:** Updates all dependencies that cause npm audit to issue a warning ([6ef5707](6ef5707))

### Features

* `.type` property on `Error`s emitted from connections ([#1126](#1126)) ([debe7a6](debe7a6))
* `PeerError` from connections ([ad3a0cb](ad3a0cb))
* **DataConnection:** handle close messages and flush option ([6ca38d3](6ca38d3)), closes [#982](#982)
* **MediaChannel:** Add experimental `willCloseOnRemote` event to MediaConnection. ([ed84829](ed84829))
* MsgPack/Cbor serialization ([fcffbf2](fcffbf2))
* MsgPack/Cbor serialization ([#1120](#1120)) ([4367256](4367256)), closes [#611](#611)
@jonasgloning
Copy link
Member

I've published the update in version v1.5 on npm now.


I’m sorry it took so long. And I’m deeply sorry for the lack of communication on my part.

Despite the correctness of the patch, it didn't work consistently across different platforms and browsers on my end. I wanted to ensure its reliability, so I advanced a long-planned E2E test suite, but I significantly underestimated the time this would take me.

Months later, after setting everything up, the tests really did fail randomly. Both dde08f0 and 573d7d7, unrelated to the code of this PR, were necessary in the end – that was just a lucky guess. The code was fine all along, but there was a bug in the build process.

The test suite indicates the close events still aren’t consistently emitted on old Chrome versions. However, since they function well on modern versions and on Firefox, I'm attributing this to a browser bug.

I didn't have anything to update you with other than "blocked on something unrelated" and "should be working, isn’t for unknown reasons" and so I didn’t. However, I should have kept you updated regardless. I will strive to be better next time.

github-actions bot pushed a commit that referenced this issue Dec 3, 2023
## [1.5.2-rc.1](v1.5.1...v1.5.2-rc.1) (2023-12-03)

### Bug Fixes

* `close` event was not triggered reliably ([#860](#860)) ([ec1d5ae](ec1d5ae)), closes [#636](#636)
* **datachannel:** sending order is now preserved correctly ([18d491a](18d491a)), closes [#746](#746)
* support Blobs nested in objects ([7956dd6](7956dd6)), closes [#1163](#1163)
@peers peers deleted a comment from github-actions bot Dec 3, 2023
@peers peers locked as resolved and limited conversation to collaborators Dec 3, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.