main.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. // pion-to-pion is an example of two pion instances communicating directly!
  4. package main
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "flag"
  9. "fmt"
  10. "io/ioutil"
  11. "net/http"
  12. "os"
  13. "sync"
  14. "time"
  15. "github.com/pion/webrtc/v3"
  16. "github.com/pion/webrtc/v3/examples/internal/signal"
  17. )
  18. func signalCandidate(addr string, c *webrtc.ICECandidate) error {
  19. payload := []byte(c.ToJSON().Candidate)
  20. resp, err := http.Post(fmt.Sprintf("http://%s/candidate", addr), // nolint:noctx
  21. "application/json; charset=utf-8", bytes.NewReader(payload))
  22. if err != nil {
  23. return err
  24. }
  25. return resp.Body.Close()
  26. }
  27. func main() { // nolint:gocognit
  28. offerAddr := flag.String("offer-address", "localhost:50000", "Address that the Offer HTTP server is hosted on.")
  29. answerAddr := flag.String("answer-address", ":60000", "Address that the Answer HTTP server is hosted on.")
  30. flag.Parse()
  31. var candidatesMux sync.Mutex
  32. pendingCandidates := make([]*webrtc.ICECandidate, 0)
  33. // Everything below is the Pion WebRTC API! Thanks for using it ❤️.
  34. // Prepare the configuration
  35. config := webrtc.Configuration{
  36. ICEServers: []webrtc.ICEServer{
  37. {
  38. URLs: []string{"stun:stun.l.google.com:19302"},
  39. },
  40. },
  41. }
  42. // Create a new RTCPeerConnection
  43. peerConnection, err := webrtc.NewPeerConnection(config)
  44. if err != nil {
  45. panic(err)
  46. }
  47. defer func() {
  48. if err := peerConnection.Close(); err != nil {
  49. fmt.Printf("cannot close peerConnection: %v\n", err)
  50. }
  51. }()
  52. // When an ICE candidate is available send to the other Pion instance
  53. // the other Pion instance will add this candidate by calling AddICECandidate
  54. peerConnection.OnICECandidate(func(c *webrtc.ICECandidate) {
  55. if c == nil {
  56. return
  57. }
  58. candidatesMux.Lock()
  59. defer candidatesMux.Unlock()
  60. desc := peerConnection.RemoteDescription()
  61. if desc == nil {
  62. pendingCandidates = append(pendingCandidates, c)
  63. } else if onICECandidateErr := signalCandidate(*offerAddr, c); onICECandidateErr != nil {
  64. panic(onICECandidateErr)
  65. }
  66. })
  67. // A HTTP handler that allows the other Pion instance to send us ICE candidates
  68. // This allows us to add ICE candidates faster, we don't have to wait for STUN or TURN
  69. // candidates which may be slower
  70. http.HandleFunc("/candidate", func(w http.ResponseWriter, r *http.Request) {
  71. candidate, candidateErr := ioutil.ReadAll(r.Body)
  72. if candidateErr != nil {
  73. panic(candidateErr)
  74. }
  75. if candidateErr := peerConnection.AddICECandidate(webrtc.ICECandidateInit{Candidate: string(candidate)}); candidateErr != nil {
  76. panic(candidateErr)
  77. }
  78. })
  79. // A HTTP handler that processes a SessionDescription given to us from the other Pion process
  80. http.HandleFunc("/sdp", func(w http.ResponseWriter, r *http.Request) {
  81. sdp := webrtc.SessionDescription{}
  82. if err := json.NewDecoder(r.Body).Decode(&sdp); err != nil {
  83. panic(err)
  84. }
  85. if err := peerConnection.SetRemoteDescription(sdp); err != nil {
  86. panic(err)
  87. }
  88. // Create an answer to send to the other process
  89. answer, err := peerConnection.CreateAnswer(nil)
  90. if err != nil {
  91. panic(err)
  92. }
  93. // Send our answer to the HTTP server listening in the other process
  94. payload, err := json.Marshal(answer)
  95. if err != nil {
  96. panic(err)
  97. }
  98. resp, err := http.Post(fmt.Sprintf("http://%s/sdp", *offerAddr), "application/json; charset=utf-8", bytes.NewReader(payload)) // nolint:noctx
  99. if err != nil {
  100. panic(err)
  101. } else if closeErr := resp.Body.Close(); closeErr != nil {
  102. panic(closeErr)
  103. }
  104. // Sets the LocalDescription, and starts our UDP listeners
  105. err = peerConnection.SetLocalDescription(answer)
  106. if err != nil {
  107. panic(err)
  108. }
  109. candidatesMux.Lock()
  110. for _, c := range pendingCandidates {
  111. onICECandidateErr := signalCandidate(*offerAddr, c)
  112. if onICECandidateErr != nil {
  113. panic(onICECandidateErr)
  114. }
  115. }
  116. candidatesMux.Unlock()
  117. })
  118. // Set the handler for Peer connection state
  119. // This will notify you when the peer has connected/disconnected
  120. peerConnection.OnConnectionStateChange(func(s webrtc.PeerConnectionState) {
  121. fmt.Printf("Peer Connection State has changed: %s\n", s.String())
  122. if s == webrtc.PeerConnectionStateFailed {
  123. // Wait until PeerConnection has had no network activity for 30 seconds or another failure. It may be reconnected using an ICE Restart.
  124. // Use webrtc.PeerConnectionStateDisconnected if you are interested in detecting faster timeout.
  125. // Note that the PeerConnection may come back from PeerConnectionStateDisconnected.
  126. fmt.Println("Peer Connection has gone to failed exiting")
  127. os.Exit(0)
  128. }
  129. })
  130. // Register data channel creation handling
  131. peerConnection.OnDataChannel(func(d *webrtc.DataChannel) {
  132. fmt.Printf("New DataChannel %s %d\n", d.Label(), d.ID())
  133. // Register channel opening handling
  134. d.OnOpen(func() {
  135. fmt.Printf("Data channel '%s'-'%d' open. Random messages will now be sent to any connected DataChannels every 5 seconds\n", d.Label(), d.ID())
  136. for range time.NewTicker(5 * time.Second).C {
  137. message := signal.RandSeq(15)
  138. fmt.Printf("Sending '%s'\n", message)
  139. // Send the message as text
  140. sendTextErr := d.SendText(message)
  141. if sendTextErr != nil {
  142. panic(sendTextErr)
  143. }
  144. }
  145. })
  146. // Register text message handling
  147. d.OnMessage(func(msg webrtc.DataChannelMessage) {
  148. fmt.Printf("Message from DataChannel '%s': '%s'\n", d.Label(), string(msg.Data))
  149. })
  150. })
  151. // Start HTTP server that accepts requests from the offer process to exchange SDP and Candidates
  152. // nolint: gosec
  153. panic(http.ListenAndServe(*answerAddr, nil))
  154. }