WEBRTC: Called in wrong state: stable

Viewed 32

I am working on a project that use WebRTC. Think different browsers. 2 different user in a same room. Then click the user from browser 1. When I click that function works:

(pc declared as newRTCPeerConnection(webRTCIceServers))

 const dc = pc.createDataChannel("channel")
        dc.onopen = e => console.log("connection opened")
        const offer = await pc.createOffer();
        await pc.setLocalDescription(offer)
        socket.emit("client description", { nickname: nickname, description: JSON.stringify(pc.localDescription) })

After that in backend I wrote socket as :

socket.on("client description", (res) => {
    if(JSON.parse(res.description).type === 'offer'){
      Object.keys(rooms).forEach((key, index) => {
        rooms[key].map((item, i) => {
          if (item.nickname === res.nickname) {
             socket.broadcast.to(item.id).emit("get description", {id: socket.id, description: JSON.parse(res.description)})
          }
        })
      })
    }else if(JSON.parse(res.description).type === 'answer'){
      socket.broadcast.to(res.id).emit("get description",{description: JSON.parse(res.description)} )
    }
  })

then I tried to catch answer in frontend with use effect.

  useEffect(() => {
        socket.on("get description", async (res: offerResponse) => {
            console.log(res, 'ne geliyo')

            if (res.description) {
                console.log('answer set mi')
                await pc.setRemoteDescription(res.description)
                if (res.description.type == 'offer') {
                    await pc.setLocalDescription(await pc.createAnswer());
                    socket.emit("client description", { id: res.id, description: JSON.stringify(pc.localDescription) })
                } else if (res.description.type === "answer") {
                    pc.setRemoteDescription(res.description)
                }
            }
        })
    }, [])

HOWEVER, both browsers return error: browser 1(which sends offer) returns "Uncaught (in promise) DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable"

AND, browser 2(gets offer and returns answer) return error: Uncaught (in promise) DOMException: Failed to execute 'setLocalDescription' on 'RTCPeerConnection': Failed to set local answer sdp: Called in wrong state: stable

How can I fix this? If I write socket.signalingState !== 'stable not working at all.

0 Answers
Related