main.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. // ice-restart demonstrates Pion WebRTC's ICE Restart abilities.
  4. package main
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "time"
  10. "github.com/pion/webrtc/v3"
  11. )
  12. var peerConnection *webrtc.PeerConnection //nolint
  13. func doSignaling(w http.ResponseWriter, r *http.Request) {
  14. var err error
  15. if peerConnection == nil {
  16. if peerConnection, err = webrtc.NewPeerConnection(webrtc.Configuration{}); err != nil {
  17. panic(err)
  18. }
  19. // Set the handler for ICE connection state
  20. // This will notify you when the peer has connected/disconnected
  21. peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
  22. fmt.Printf("ICE Connection State has changed: %s\n", connectionState.String())
  23. })
  24. // Send the current time via a DataChannel to the remote peer every 3 seconds
  25. peerConnection.OnDataChannel(func(d *webrtc.DataChannel) {
  26. d.OnOpen(func() {
  27. for range time.Tick(time.Second * 3) {
  28. if err = d.SendText(time.Now().String()); err != nil {
  29. panic(err)
  30. }
  31. }
  32. })
  33. })
  34. }
  35. var offer webrtc.SessionDescription
  36. if err = json.NewDecoder(r.Body).Decode(&offer); err != nil {
  37. panic(err)
  38. }
  39. if err = peerConnection.SetRemoteDescription(offer); err != nil {
  40. panic(err)
  41. }
  42. // Create channel that is blocked until ICE Gathering is complete
  43. gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
  44. answer, err := peerConnection.CreateAnswer(nil)
  45. if err != nil {
  46. panic(err)
  47. } else if err = peerConnection.SetLocalDescription(answer); err != nil {
  48. panic(err)
  49. }
  50. // Block until ICE Gathering is complete, disabling trickle ICE
  51. // we do this because we only can exchange one signaling message
  52. // in a production application you should exchange ICE Candidates via OnICECandidate
  53. <-gatherComplete
  54. response, err := json.Marshal(*peerConnection.LocalDescription())
  55. if err != nil {
  56. panic(err)
  57. }
  58. w.Header().Set("Content-Type", "application/json")
  59. if _, err := w.Write(response); err != nil {
  60. panic(err)
  61. }
  62. }
  63. func main() {
  64. http.Handle("/", http.FileServer(http.Dir(".")))
  65. http.HandleFunc("/doSignaling", doSignaling)
  66. fmt.Println("Open http://localhost:8080 to access this demo")
  67. // nolint: gosec
  68. panic(http.ListenAndServe(":8080", nil))
  69. }