github.com/pion/webrtc/v4@v4.0.1/gathering_complete_promise_example_test.go (about)

     1  // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
     2  // SPDX-License-Identifier: MIT
     3  
     4  package webrtc
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  )
    10  
    11  // ExampleGatheringCompletePromise demonstrates how to implement
    12  // non-trickle ICE in Pion, an older form of ICE that does not require an
    13  // asynchronous side channel between peers: negotiation is just a single
    14  // offer-answer exchange.  It works by explicitly waiting for all local
    15  // ICE candidates to have been gathered before sending an offer to the peer.
    16  func ExampleGatheringCompletePromise() {
    17  	// create a peer connection
    18  	pc, err := NewPeerConnection(Configuration{})
    19  	if err != nil {
    20  		panic(err)
    21  	}
    22  	defer func() {
    23  		closeErr := pc.Close()
    24  		if closeErr != nil {
    25  			panic(closeErr)
    26  		}
    27  	}()
    28  
    29  	// add at least one transceiver to the peer connection, or nothing
    30  	// interesting will happen.  This could use pc.AddTrack instead.
    31  	_, err = pc.AddTransceiverFromKind(RTPCodecTypeVideo)
    32  	if err != nil {
    33  		panic(err)
    34  	}
    35  
    36  	// create a first offer that does not contain any local candidates
    37  	offer, err := pc.CreateOffer(nil)
    38  	if err != nil {
    39  		panic(err)
    40  	}
    41  
    42  	// gatherComplete is a channel that will be closed when
    43  	// the gathering of local candidates is complete.
    44  	gatherComplete := GatheringCompletePromise(pc)
    45  
    46  	// apply the offer
    47  	err = pc.SetLocalDescription(offer)
    48  	if err != nil {
    49  		panic(err)
    50  	}
    51  
    52  	// wait for gathering of local candidates to complete
    53  	<-gatherComplete
    54  
    55  	// compute the local offer again
    56  	offer2 := pc.LocalDescription()
    57  
    58  	// this second offer contains all candidates, and may be sent to
    59  	// the peer with no need for further communication.  In this
    60  	// example, we simply check that it contains at least one
    61  	// candidate.
    62  	hasCandidate := strings.Contains(offer2.SDP, "\na=candidate:")
    63  	if hasCandidate {
    64  		fmt.Println("Ok!")
    65  	}
    66  	// Output: Ok!
    67  }