Skip to content

Instantly share code, notes, and snippets.

@poga
Created April 9, 2019 06:25
Show Gist options
  • Save poga/870c7f65a00c5f57d56086e57873e964 to your computer and use it in GitHub Desktop.
Save poga/870c7f65a00c5f57d56086e57873e964 to your computer and use it in GitHub Desktop.
pion-to-pion example, passing description without http server
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"time"
"strings"
"os"
"bytes"
"bufio"
"github.com/pion/webrtc/v2"
"github.com/pion/webrtc/v2/examples/internal/signal"
)
func main() {
flag.Parse()
// 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
peerConnection, err := webrtc.NewPeerConnection(config)
if err != nil {
panic(err)
}
// Set the handler for ICE connection state
// This will notify you when the peer has connected/disconnected
peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
fmt.Printf("ICE Connection State has changed: %s\n", connectionState.String())
})
// Register data channel creation handling
peerConnection.OnDataChannel(func(d *webrtc.DataChannel) {
fmt.Printf("New DataChannel %s %d\n", d.Label(), d.ID())
// Register channel opening handling
d.OnOpen(func() {
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())
for range time.NewTicker(5 * time.Second).C {
message := signal.RandSeq(15)
fmt.Printf("Sending '%s'\n", message)
// Send the message as text
sendTextErr := d.SendText(message)
if sendTextErr != nil {
panic(sendTextErr)
}
}
})
// Register text message handling
d.OnMessage(func(msg webrtc.DataChannelMessage) {
fmt.Printf("Message from DataChannel '%s': '%s'\n", d.Label(), string(msg.Data))
})
})
var offerText string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
offerText = scanner.Text()
fmt.Println("read", offerText)
break
}
if scanner.Err() != nil {
panic(scanner.Err())
}
var offer webrtc.SessionDescription
err = json.NewDecoder(strings.NewReader(offerText)).Decode(&offer)
// Exchange the offer/answer via HTTP
// offerChan, answerChan := mustSignalViaHTTP(*addr)
// Wait for the remote SessionDescription
// offer = <-offerChan
fmt.Println(offer)
err = peerConnection.SetRemoteDescription(offer)
if err != nil {
panic(err)
}
// Create answer
answer, err := peerConnection.CreateAnswer(nil)
if err != nil {
panic(err)
}
answerBuf := new(bytes.Buffer)
err = json.NewEncoder(answerBuf).Encode(answer)
if err != nil {
panic(err)
}
println(answerBuf.String())
// Sets the LocalDescription, and starts our UDP listeners
err = peerConnection.SetLocalDescription(answer)
if err != nil {
panic(err)
}
// Send the answer
// answerChan <- answer
// Block forever
select {}
}
// mustSignalViaHTTP exchange the SDP offer and answer using an HTTP server.
func mustSignalViaHTTP(address string) (offerOut chan webrtc.SessionDescription, answerIn chan webrtc.SessionDescription) {
offerOut = make(chan webrtc.SessionDescription)
answerIn = make(chan webrtc.SessionDescription)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var offer webrtc.SessionDescription
err := json.NewDecoder(r.Body).Decode(&offer)
if err != nil {
panic(err)
}
offerOut <- offer
answer := <-answerIn
err = json.NewEncoder(w).Encode(answer)
if err != nil {
panic(err)
}
})
go func() {
panic(http.ListenAndServe(address, nil))
}()
fmt.Println("Listening on", address)
return
}
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"bufio"
"strings"
"time"
"github.com/pion/webrtc/v2"
"github.com/pion/webrtc/v2/examples/internal/signal"
)
func main() {
flag.Parse()
// 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
peerConnection, err := webrtc.NewPeerConnection(config)
if err != nil {
panic(err)
}
// Create a datachannel with label 'data'
dataChannel, err := peerConnection.CreateDataChannel("data", nil)
if err != nil {
panic(err)
}
// Set the handler for ICE connection state
// This will notify you when the peer has connected/disconnected
peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
fmt.Printf("ICE Connection State has changed: %s\n", connectionState.String())
})
// Register channel opening handling
dataChannel.OnOpen(func() {
fmt.Printf("Data channel '%s'-'%d' open. Random messages will now be sent to any connected DataChannels every 5 seconds\n", dataChannel.Label(), dataChannel.ID())
for range time.NewTicker(5 * time.Second).C {
message := signal.RandSeq(15)
fmt.Printf("Sending '%s'\n", message)
// Send the message as text
sendTextErr := dataChannel.SendText(message)
if sendTextErr != nil {
panic(sendTextErr)
}
}
})
// Register text message handling
dataChannel.OnMessage(func(msg webrtc.DataChannelMessage) {
fmt.Printf("Message from DataChannel '%s': '%s'\n", dataChannel.Label(), string(msg.Data))
})
// Create an offer to send to the browser
offer, err := peerConnection.CreateOffer(nil)
if err != nil {
panic(err)
}
// Sets the LocalDescription, and starts our UDP listeners
err = peerConnection.SetLocalDescription(offer)
if err != nil {
panic(err)
}
b := new (bytes.Buffer)
err = json.NewEncoder(b).Encode(offer)
if err != nil {
panic(err)
}
fmt.Println(b)
// Exchange the offer for the answer
// answer := mustSignalViaHTTP(offer, *addr)
var answerText string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
answerText = scanner.Text()
fmt.Println("read", answerText)
}
if scanner.Err() != nil {
panic(scanner.Err())
}
var answer webrtc.SessionDescription
err = json.NewDecoder(strings.NewReader(answerText)).Decode(&answer)
if err != nil {
panic(err)
}
// Apply the answer as the remote description
err = peerConnection.SetRemoteDescription(answer)
if err != nil {
panic(err)
}
// Block forever
select {}
}
// mustSignalViaHTTP exchange the SDP offer and answer using an HTTP Post request.
func mustSignalViaHTTP(offer webrtc.SessionDescription, address string) webrtc.SessionDescription {
b := new(bytes.Buffer)
err := json.NewEncoder(b).Encode(offer)
if err != nil {
panic(err)
}
resp, err := http.Post("http://"+address, "application/json; charset=utf-8", b)
if err != nil {
panic(err)
}
defer func() {
closeErr := resp.Body.Close()
if closeErr != nil {
panic(closeErr)
}
}()
var answer webrtc.SessionDescription
err = json.NewDecoder(resp.Body).Decode(&answer)
if err != nil {
panic(err)
}
return answer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment