main.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. // data-channels is a Pion WebRTC application that shows how you can send/recv DataChannel messages from a web browser
  4. package main
  5. import (
  6. "fmt"
  7. "os"
  8. "time"
  9. "github.com/pion/webrtc/v3"
  10. "github.com/pion/webrtc/v3/examples/internal/signal"
  11. )
  12. func main() {
  13. // Everything below is the Pion WebRTC API! Thanks for using it ❤️.
  14. // Prepare the configuration
  15. config := webrtc.Configuration{
  16. ICEServers: []webrtc.ICEServer{
  17. {
  18. URLs: []string{"stun:stun.l.google.com:19302"},
  19. },
  20. },
  21. }
  22. // Create a new RTCPeerConnection
  23. peerConnection, err := webrtc.NewPeerConnection(config)
  24. if err != nil {
  25. panic(err)
  26. }
  27. defer func() {
  28. if cErr := peerConnection.Close(); cErr != nil {
  29. fmt.Printf("cannot close peerConnection: %v\n", cErr)
  30. }
  31. }()
  32. // Set the handler for Peer connection state
  33. // This will notify you when the peer has connected/disconnected
  34. peerConnection.OnConnectionStateChange(func(s webrtc.PeerConnectionState) {
  35. fmt.Printf("Peer Connection State has changed: %s\n", s.String())
  36. if s == webrtc.PeerConnectionStateFailed {
  37. // Wait until PeerConnection has had no network activity for 30 seconds or another failure. It may be reconnected using an ICE Restart.
  38. // Use webrtc.PeerConnectionStateDisconnected if you are interested in detecting faster timeout.
  39. // Note that the PeerConnection may come back from PeerConnectionStateDisconnected.
  40. fmt.Println("Peer Connection has gone to failed exiting")
  41. os.Exit(0)
  42. }
  43. })
  44. // Register data channel creation handling
  45. peerConnection.OnDataChannel(func(d *webrtc.DataChannel) {
  46. fmt.Printf("New DataChannel %s %d\n", d.Label(), d.ID())
  47. // Register channel opening handling
  48. d.OnOpen(func() {
  49. 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())
  50. for range time.NewTicker(5 * time.Second).C {
  51. message := signal.RandSeq(15)
  52. fmt.Printf("Sending '%s'\n", message)
  53. // Send the message as text
  54. sendErr := d.SendText(message)
  55. if sendErr != nil {
  56. panic(sendErr)
  57. }
  58. }
  59. })
  60. // Register text message handling
  61. d.OnMessage(func(msg webrtc.DataChannelMessage) {
  62. fmt.Printf("Message from DataChannel '%s': '%s'\n", d.Label(), string(msg.Data))
  63. })
  64. })
  65. // Wait for the offer to be pasted
  66. offer := webrtc.SessionDescription{}
  67. signal.Decode(signal.MustReadStdin(), &offer)
  68. // Set the remote SessionDescription
  69. err = peerConnection.SetRemoteDescription(offer)
  70. if err != nil {
  71. panic(err)
  72. }
  73. // Create an answer
  74. answer, err := peerConnection.CreateAnswer(nil)
  75. if err != nil {
  76. panic(err)
  77. }
  78. // Create channel that is blocked until ICE Gathering is complete
  79. gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
  80. // Sets the LocalDescription, and starts our UDP listeners
  81. err = peerConnection.SetLocalDescription(answer)
  82. if err != nil {
  83. panic(err)
  84. }
  85. // Block until ICE Gathering is complete, disabling trickle ICE
  86. // we do this because we only can exchange one signaling message
  87. // in a production application you should exchange ICE Candidates via OnICECandidate
  88. <-gatherComplete
  89. // Output the answer in base64 so we can paste it in browser
  90. fmt.Println(signal.Encode(*peerConnection.LocalDescription()))
  91. // Block forever
  92. select {}
  93. }