snapshot of https://github.com/pion/webrtc.git (main, 2026-09-15; blobs > 131072B omitted)
Some checks failed
REUSE Compliance Check / lint (push) Failing after 0s
Browser E2E / Test (push) Failing after 3s
Test / test (1.24) (push) Failing after 0s
Test / test-i386 (1.25) (push) Failing after 0s
Test / test-i386 (1.24) (push) Failing after 0s
Test / test-windows (1.25) (push) Failing after 0s
Test / test-windows (1.24) (push) Failing after 0s
Test / test (1.25) (push) Failing after 0s
Examples Tests / Test (push) Failing after 3s
Test / test-macos (1.25) (push) Failing after 0s
Test / test-macos (1.24) (push) Failing after 0s
Go mod tidy / tidy (push) Failing after 0s
Test / test-wasm (push) Failing after 0s
CodeQL / analyze (push) Failing after 1s
Fuzz / fuzz (push) Failing after 0s
Some checks failed
REUSE Compliance Check / lint (push) Failing after 0s
Browser E2E / Test (push) Failing after 3s
Test / test (1.24) (push) Failing after 0s
Test / test-i386 (1.25) (push) Failing after 0s
Test / test-i386 (1.24) (push) Failing after 0s
Test / test-windows (1.25) (push) Failing after 0s
Test / test-windows (1.24) (push) Failing after 0s
Test / test (1.25) (push) Failing after 0s
Examples Tests / Test (push) Failing after 3s
Test / test-macos (1.25) (push) Failing after 0s
Test / test-macos (1.24) (push) Failing after 0s
Go mod tidy / tidy (push) Failing after 0s
Test / test-wasm (push) Failing after 0s
CodeQL / analyze (push) Failing after 1s
Fuzz / fuzz (push) Failing after 0s
This commit is contained in:
12
examples/data-channels-detach/README.md
Normal file
12
examples/data-channels-detach/README.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# data-channels-detach
|
||||
data-channels-detach is an example that shows how you can detach a data channel. This allows direct access 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.
|
||||
|
||||
The example mirrors the data-channels example.
|
||||
|
||||
## Install
|
||||
```
|
||||
go install github.com/pion/webrtc/v4/examples/data-channels-detach@latest
|
||||
```
|
||||
|
||||
## Usage
|
||||
The example can be used in the same way as the data-channel example or can be paired with the data-channels-detach-create example. In the latter case; run both example and exchange the offer/answer text by copy-pasting them on the other terminal.
|
||||
8
examples/data-channels-detach/jsfiddle/demo.css
Normal file
8
examples/data-channels-detach/jsfiddle/demo.css
Normal file
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
|
||||
SPDX-License-Identifier: MIT
|
||||
*/
|
||||
textarea {
|
||||
width: 500px;
|
||||
min-height: 75px;
|
||||
}
|
||||
20
examples/data-channels-detach/jsfiddle/demo.html
Normal file
20
examples/data-channels-detach/jsfiddle/demo.html
Normal file
@@ -0,0 +1,20 @@
|
||||
<!--
|
||||
SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
|
||||
SPDX-License-Identifier: MIT
|
||||
-->
|
||||
Browser base64 Session Description<br />
|
||||
<textarea id="localSessionDescription" readonly="true"></textarea> <br />
|
||||
|
||||
Golang base64 Session Description<br />
|
||||
<textarea id="remoteSessionDescription"></textarea><br/>
|
||||
<button onclick="window.startSession()">Start Session</button><br />
|
||||
|
||||
<br />
|
||||
|
||||
<!--Message<br />
|
||||
<textarea id="message">This is my DataChannel message!</textarea> <br/>
|
||||
<button onclick="window.sendMessage()">Send Message</button> <br />-->
|
||||
|
||||
<br />
|
||||
Logs<br />
|
||||
<div id="logs"></div>
|
||||
231
examples/data-channels-detach/jsfiddle/main.go
Normal file
231
examples/data-channels-detach/jsfiddle/main.go
Normal file
@@ -0,0 +1,231 @@
|
||||
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build js && wasm
|
||||
// +build js,wasm
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall/js"
|
||||
"time"
|
||||
|
||||
"github.com/pion/randutil"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
const messageSize = 15
|
||||
|
||||
func main() {
|
||||
// Since this behavior diverges from the WebRTC API it has to be
|
||||
// enabled using a settings engine. Mixing both detached and the
|
||||
// OnMessage DataChannel API is not supported.
|
||||
|
||||
// Create a SettingEngine and enable Detach
|
||||
s := webrtc.SettingEngine{}
|
||||
s.DetachDataChannels()
|
||||
|
||||
// Create an API object with the engine
|
||||
api := webrtc.NewAPI(webrtc.WithSettingEngine(s))
|
||||
|
||||
// Everything below is the Pion WebRTC API! Thanks for using it ❤️.
|
||||
|
||||
// Prepare the configuration
|
||||
config := webrtc.Configuration{
|
||||
ICEServers: []webrtc.ICEServer{
|
||||
{
|
||||
URLs: []string{"stun:stun.l.google.com:19302"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Create a new RTCPeerConnection using the API object
|
||||
peerConnection, err := api.NewPeerConnection(config)
|
||||
if err != nil {
|
||||
handleError(err)
|
||||
}
|
||||
|
||||
// Create a datachannel with label 'data'
|
||||
dataChannel, err := peerConnection.CreateDataChannel("data", nil)
|
||||
if err != nil {
|
||||
handleError(err)
|
||||
}
|
||||
|
||||
// Set the handler for ICE connection state
|
||||
// This will notify you when the peer has connected/disconnected
|
||||
peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
|
||||
log(fmt.Sprintf("ICE Connection State has changed: %s\n", connectionState.String()))
|
||||
})
|
||||
|
||||
// Register channel opening handling
|
||||
dataChannel.OnOpen(func() {
|
||||
log(fmt.Sprintf("Data channel '%s'-'%d' open.\n", dataChannel.Label(), dataChannel.ID()))
|
||||
|
||||
// Detach the data channel
|
||||
raw, dErr := dataChannel.Detach()
|
||||
if dErr != nil {
|
||||
handleError(dErr)
|
||||
}
|
||||
|
||||
// Handle reading from the data channel
|
||||
go ReadLoop(raw)
|
||||
|
||||
// Handle writing to the data channel
|
||||
go WriteLoop(raw)
|
||||
})
|
||||
|
||||
// Create an offer to send to the browser
|
||||
offer, err := peerConnection.CreateOffer(nil)
|
||||
if err != nil {
|
||||
handleError(err)
|
||||
}
|
||||
|
||||
// Sets the LocalDescription, and starts our UDP listeners
|
||||
err = peerConnection.SetLocalDescription(offer)
|
||||
if err != nil {
|
||||
handleError(err)
|
||||
}
|
||||
|
||||
// Add handlers for setting up the connection.
|
||||
peerConnection.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
|
||||
log(fmt.Sprint(state))
|
||||
})
|
||||
peerConnection.OnICECandidate(func(candidate *webrtc.ICECandidate) {
|
||||
if candidate != nil {
|
||||
encodedDescr := encode(peerConnection.LocalDescription())
|
||||
el := getElementByID("localSessionDescription")
|
||||
el.Set("value", encodedDescr)
|
||||
}
|
||||
})
|
||||
|
||||
// Set up global callbacks which will be triggered on button clicks.
|
||||
/*js.Global().Set("sendMessage", js.FuncOf(func(_ js.Value, _ []js.Value) any {
|
||||
go func() {
|
||||
el := getElementByID("message")
|
||||
message := el.Get("value").String()
|
||||
if message == "" {
|
||||
js.Global().Call("alert", "Message must not be empty")
|
||||
return
|
||||
}
|
||||
if err := sendChannel.SendText(message); err != nil {
|
||||
handleError(err)
|
||||
}
|
||||
}()
|
||||
return js.Undefined()
|
||||
}))*/
|
||||
js.Global().Set("startSession", js.FuncOf(func(_ js.Value, _ []js.Value) any {
|
||||
go func() {
|
||||
el := getElementByID("remoteSessionDescription")
|
||||
sd := el.Get("value").String()
|
||||
if sd == "" {
|
||||
js.Global().Call("alert", "Session Description must not be empty")
|
||||
return
|
||||
}
|
||||
|
||||
descr := webrtc.SessionDescription{}
|
||||
decode(sd, &descr)
|
||||
if err := peerConnection.SetRemoteDescription(descr); err != nil {
|
||||
handleError(err)
|
||||
}
|
||||
}()
|
||||
return js.Undefined()
|
||||
}))
|
||||
|
||||
// Block forever
|
||||
select {}
|
||||
}
|
||||
|
||||
// ReadLoop shows how to read from the datachannel directly
|
||||
func ReadLoop(d io.Reader) {
|
||||
for {
|
||||
buffer := make([]byte, messageSize)
|
||||
n, err := d.Read(buffer)
|
||||
if err != nil {
|
||||
log(fmt.Sprintf("Datachannel closed; Exit the readloop: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
log(fmt.Sprintf("Message from DataChannel: %s\n", string(buffer[:n])))
|
||||
}
|
||||
}
|
||||
|
||||
// WriteLoop shows how to write to the datachannel directly
|
||||
func WriteLoop(d io.Writer) {
|
||||
ticker := time.NewTicker(5 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
message, err := randutil.GenerateCryptoRandomString(messageSize, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||
if err != nil {
|
||||
handleError(err)
|
||||
}
|
||||
|
||||
log(fmt.Sprintf("Sending %s \n", message))
|
||||
if _, err := d.Write([]byte(message)); err != nil {
|
||||
handleError(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func log(msg string) {
|
||||
el := getElementByID("logs")
|
||||
el.Set("innerHTML", el.Get("innerHTML").String()+msg+"<br>")
|
||||
}
|
||||
|
||||
func handleError(err error) {
|
||||
log("Unexpected error. Check console.")
|
||||
panic(err)
|
||||
}
|
||||
|
||||
func getElementByID(id string) js.Value {
|
||||
return js.Global().Get("document").Call("getElementById", id)
|
||||
}
|
||||
|
||||
// Read from stdin until we get a newline
|
||||
func readUntilNewline() (in string) {
|
||||
var err error
|
||||
|
||||
r := bufio.NewReader(os.Stdin)
|
||||
for {
|
||||
in, err = r.ReadString('\n')
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if in = strings.TrimSpace(in); len(in) > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("")
|
||||
return
|
||||
}
|
||||
|
||||
// JSON encode + base64 a SessionDescription
|
||||
func encode(obj *webrtc.SessionDescription) string {
|
||||
b, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// Decode a base64 and unmarshal JSON into a SessionDescription
|
||||
func decode(in string, obj *webrtc.SessionDescription) {
|
||||
b, err := base64.StdEncoding.DecodeString(in)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(b, obj); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
216
examples/data-channels-detach/main.go
Normal file
216
examples/data-channels-detach/main.go
Normal file
@@ -0,0 +1,216 @@
|
||||
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// data-channels-detach is an example that shows how you can detach a data channel.
|
||||
// This allows direct access 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.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pion/randutil"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
const messageSize = 15
|
||||
|
||||
func main() {
|
||||
// Since this behavior diverges from the WebRTC API it has to be
|
||||
// enabled using a settings engine. Mixing both detached and the
|
||||
// OnMessage DataChannel API is not supported.
|
||||
|
||||
// Create a SettingEngine and enable Detach
|
||||
s := webrtc.SettingEngine{}
|
||||
s.DetachDataChannels()
|
||||
|
||||
// Create an API object with the engine
|
||||
api := webrtc.NewAPI(webrtc.WithSettingEngine(s))
|
||||
|
||||
// Everything below is the Pion WebRTC API! Thanks for using it ❤️.
|
||||
|
||||
// Prepare the configuration
|
||||
config := webrtc.Configuration{
|
||||
ICEServers: []webrtc.ICEServer{
|
||||
{
|
||||
URLs: []string{"stun:stun.l.google.com:19302"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Create a new RTCPeerConnection using the API object
|
||||
peerConnection, err := api.NewPeerConnection(config)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer func() {
|
||||
if cErr := peerConnection.Close(); cErr != nil {
|
||||
fmt.Printf("cannot close peerConnection: %v\n", cErr)
|
||||
}
|
||||
}()
|
||||
|
||||
// Set the handler for Peer connection state
|
||||
// This will notify you when the peer has connected/disconnected
|
||||
peerConnection.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
||||
fmt.Printf("Peer Connection State has changed: %s\n", state.String())
|
||||
|
||||
if state == webrtc.PeerConnectionStateFailed {
|
||||
// Wait until PeerConnection has had no network activity for 30 seconds or another failure.
|
||||
// It may be reconnected using an ICE Restart.
|
||||
// Use webrtc.PeerConnectionStateDisconnected if you are interested in detecting faster timeout.
|
||||
// Note that the PeerConnection may come back from PeerConnectionStateDisconnected.
|
||||
fmt.Println("Peer Connection has gone to failed exiting")
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
if state == webrtc.PeerConnectionStateClosed {
|
||||
// PeerConnection was explicitly closed. This usually happens from a DTLS CloseNotify
|
||||
fmt.Println("Peer Connection has gone to closed exiting")
|
||||
os.Exit(0)
|
||||
}
|
||||
})
|
||||
|
||||
// Register data channel creation handling
|
||||
peerConnection.OnDataChannel(func(dataChannel *webrtc.DataChannel) {
|
||||
fmt.Printf("New DataChannel %s %d\n", dataChannel.Label(), dataChannel.ID())
|
||||
|
||||
// Register channel opening handling
|
||||
dataChannel.OnOpen(func() {
|
||||
fmt.Printf("Data channel '%s'-'%d' open.\n", dataChannel.Label(), dataChannel.ID())
|
||||
|
||||
// Detach the data channel
|
||||
raw, dErr := dataChannel.Detach()
|
||||
if dErr != nil {
|
||||
panic(dErr)
|
||||
}
|
||||
|
||||
// Handle reading from the data channel
|
||||
go ReadLoop(raw)
|
||||
|
||||
// Handle writing to the data channel
|
||||
go WriteLoop(raw)
|
||||
})
|
||||
})
|
||||
|
||||
// Wait for the offer to be pasted
|
||||
offer := webrtc.SessionDescription{}
|
||||
decode(readUntilNewline(), &offer)
|
||||
|
||||
// Set the remote SessionDescription
|
||||
err = peerConnection.SetRemoteDescription(offer)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Create answer
|
||||
answer, err := peerConnection.CreateAnswer(nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Create channel that is blocked until ICE Gathering is complete
|
||||
gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
|
||||
|
||||
// Sets the LocalDescription, and starts our UDP listeners
|
||||
err = peerConnection.SetLocalDescription(answer)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Block until ICE Gathering is complete, disabling trickle ICE
|
||||
// we do this because we only can exchange one signaling message
|
||||
// in a production application you should exchange ICE Candidates via OnICECandidate
|
||||
<-gatherComplete
|
||||
|
||||
// Output the answer in base64 so we can paste it in browser
|
||||
fmt.Println(encode(peerConnection.LocalDescription()))
|
||||
|
||||
// Block forever
|
||||
select {}
|
||||
}
|
||||
|
||||
// ReadLoop shows how to read from the datachannel directly.
|
||||
func ReadLoop(d io.Reader) {
|
||||
for {
|
||||
buffer := make([]byte, messageSize)
|
||||
n, err := d.Read(buffer)
|
||||
if err != nil {
|
||||
fmt.Println("Datachannel closed; Exit the readloop:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("Message from DataChannel: %s\n", string(buffer[:n]))
|
||||
}
|
||||
}
|
||||
|
||||
// WriteLoop shows how to write to the datachannel directly.
|
||||
func WriteLoop(d io.Writer) {
|
||||
ticker := time.NewTicker(5 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
message, err := randutil.GenerateCryptoRandomString(
|
||||
messageSize, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
||||
)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Printf("Sending %s \n", message)
|
||||
if _, err := d.Write([]byte(message)); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Read from stdin until we get a newline.
|
||||
func readUntilNewline() (in string) {
|
||||
var err error
|
||||
|
||||
r := bufio.NewReader(os.Stdin)
|
||||
for {
|
||||
in, err = r.ReadString('\n')
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if in = strings.TrimSpace(in); len(in) > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// JSON encode + base64 a SessionDescription.
|
||||
func encode(obj *webrtc.SessionDescription) string {
|
||||
b, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// Decode a base64 and unmarshal JSON into a SessionDescription.
|
||||
func decode(in string, obj *webrtc.SessionDescription) {
|
||||
b, err := base64.StdEncoding.DecodeString(in)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(b, obj); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user