Example #1
0
        /// <summary>
        /// Receive an RTC signalling message. If this is an offer, create an answer and transmit it. If if is an answer to an offer created elsewhere, all we have to do is set it.
        /// </summary>
        public void OnRtcMessage(Message message)
        {
            stats.lastMessageReceived = DateTime.Now.ToShortTimeString();

            if (message.type == "description")
            {
                stats.receivedSignalingMessages++;

                var sessionDescription = JsonUtility.FromJson<SessionDescriptionMessage>(message.args);
                if (sessionDescription.type == "offer")
                {
                    if (signallingState != PeerConnectionInterface.SignalingState.Stable)
                    {
                        if (!polite)
                        {
                            // Ignore the other peer's offer. Our offer will take precedence over theirs and we can expect an answer soon.
                            return;
                        }
                        else
                        {
                            pc.SetLocalDescription(new DisposableSetSessionDescriptionObserver(new SetSessionDecsriptionObserver(() =>
                            {
                                pc.SetRemoteDescription(new DisposableSetSessionDescriptionObserver(new SetSessionDecsriptionObserver(CreateAnswer)), SessionDescription.Create(SdpType.Offer, sessionDescription.sdp, IntPtr.Zero));
                            })), SessionDescription.Create(SdpType.Rollback, "", IntPtr.Zero));

                        }
                    }
                    else
                    {
                        pc.SetRemoteDescription(new DisposableSetSessionDescriptionObserver(new SetSessionDecsriptionObserver(CreateAnswer)), SessionDescription.Create(SdpType.Offer, sessionDescription.sdp, IntPtr.Zero));
                    }
                }
                else // desc.type == "answer"
                {
                    pc.SetRemoteDescription(new DisposableSetSessionDescriptionObserver(new SetSessionDecsriptionObserver()), SessionDescription.Create(SdpType.Answer, sessionDescription.sdp, IntPtr.Zero));
                }
            }

            if (message.type == "icecandidate")
            {
                stats.receivedIceMessages++;

                if (message.args == "null")
                {
                    return;
                }
                if (message.args == "")
                {
                    return;
                }

                var desc = JsonUtility.FromJson<IceCandidateMessage>(message.args);

                if (desc.candidate == "")
                {
                    return;
                }

                using (var candidate = IceCandidate.Create(desc.sdpMid, desc.sdpMlineIndex, desc.candidate, IntPtr.Zero))
                {
                    pc.AddIceCandidate(candidate);
                }
            }
        }