gathering_complete_promise_example_test.go 1.8 KB

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