main.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. // data-channels-detach is an example that shows how you can detach a data channel. This allows direct access the the underlying [pion/datachannel](https://github.com/pion/datachannel). This allows you to interact with the data channel using a more idiomatic API based on the `io.ReadWriteCloser` interface.
  4. package main
  5. import (
  6. "fmt"
  7. "io"
  8. "os"
  9. "time"
  10. "github.com/pion/webrtc/v3"
  11. "github.com/pion/webrtc/v3/examples/internal/signal"
  12. )
  13. const messageSize = 15
  14. func main() {
  15. // Since this behavior diverges from the WebRTC API it has to be
  16. // enabled using a settings engine. Mixing both detached and the
  17. // OnMessage DataChannel API is not supported.
  18. // Create a SettingEngine and enable Detach
  19. s := webrtc.SettingEngine{}
  20. s.DetachDataChannels()
  21. // Create an API object with the engine
  22. api := webrtc.NewAPI(webrtc.WithSettingEngine(s))
  23. // Everything below is the Pion WebRTC API! Thanks for using it ❤️.
  24. // Prepare the configuration
  25. config := webrtc.Configuration{
  26. ICEServers: []webrtc.ICEServer{
  27. {
  28. URLs: []string{"stun:stun.l.google.com:19302"},
  29. },
  30. },
  31. }
  32. // Create a new RTCPeerConnection using the API object
  33. peerConnection, err := api.NewPeerConnection(config)
  34. if err != nil {
  35. panic(err)
  36. }
  37. defer func() {
  38. if cErr := peerConnection.Close(); cErr != nil {
  39. fmt.Printf("cannot close peerConnection: %v\n", cErr)
  40. }
  41. }()
  42. // Set the handler for Peer connection state
  43. // This will notify you when the peer has connected/disconnected
  44. peerConnection.OnConnectionStateChange(func(s webrtc.PeerConnectionState) {
  45. fmt.Printf("Peer Connection State has changed: %s\n", s.String())
  46. if s == webrtc.PeerConnectionStateFailed {
  47. // Wait until PeerConnection has had no network activity for 30 seconds or another failure. It may be reconnected using an ICE Restart.
  48. // Use webrtc.PeerConnectionStateDisconnected if you are interested in detecting faster timeout.
  49. // Note that the PeerConnection may come back from PeerConnectionStateDisconnected.
  50. fmt.Println("Peer Connection has gone to failed exiting")
  51. os.Exit(0)
  52. }
  53. })
  54. // Register data channel creation handling
  55. peerConnection.OnDataChannel(func(d *webrtc.DataChannel) {
  56. fmt.Printf("New DataChannel %s %d\n", d.Label(), d.ID())
  57. // Register channel opening handling
  58. d.OnOpen(func() {
  59. fmt.Printf("Data channel '%s'-'%d' open.\n", d.Label(), d.ID())
  60. // Detach the data channel
  61. raw, dErr := d.Detach()
  62. if dErr != nil {
  63. panic(dErr)
  64. }
  65. // Handle reading from the data channel
  66. go ReadLoop(raw)
  67. // Handle writing to the data channel
  68. go WriteLoop(raw)
  69. })
  70. })
  71. // Wait for the offer to be pasted
  72. offer := webrtc.SessionDescription{}
  73. signal.Decode(signal.MustReadStdin(), &offer)
  74. // Set the remote SessionDescription
  75. err = peerConnection.SetRemoteDescription(offer)
  76. if err != nil {
  77. panic(err)
  78. }
  79. // Create answer
  80. answer, err := peerConnection.CreateAnswer(nil)
  81. if err != nil {
  82. panic(err)
  83. }
  84. // Create channel that is blocked until ICE Gathering is complete
  85. gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
  86. // Sets the LocalDescription, and starts our UDP listeners
  87. err = peerConnection.SetLocalDescription(answer)
  88. if err != nil {
  89. panic(err)
  90. }
  91. // Block until ICE Gathering is complete, disabling trickle ICE
  92. // we do this because we only can exchange one signaling message
  93. // in a production application you should exchange ICE Candidates via OnICECandidate
  94. <-gatherComplete
  95. // Output the answer in base64 so we can paste it in browser
  96. fmt.Println(signal.Encode(*peerConnection.LocalDescription()))
  97. // Block forever
  98. select {}
  99. }
  100. // ReadLoop shows how to read from the datachannel directly
  101. func ReadLoop(d io.Reader) {
  102. for {
  103. buffer := make([]byte, messageSize)
  104. n, err := d.Read(buffer)
  105. if err != nil {
  106. fmt.Println("Datachannel closed; Exit the readloop:", err)
  107. return
  108. }
  109. fmt.Printf("Message from DataChannel: %s\n", string(buffer[:n]))
  110. }
  111. }
  112. // WriteLoop shows how to write to the datachannel directly
  113. func WriteLoop(d io.Writer) {
  114. for range time.NewTicker(5 * time.Second).C {
  115. message := signal.RandSeq(messageSize)
  116. fmt.Printf("Sending %s \n", message)
  117. _, err := d.Write([]byte(message))
  118. if err != nil {
  119. panic(err)
  120. }
  121. }
  122. }