github.com/pion/webrtc/v4@v4.0.1/examples/data-channels/main.go (about)

     1  // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
     2  // SPDX-License-Identifier: MIT
     3  
     4  // data-channels is a Pion WebRTC application that shows how you can send/recv DataChannel messages from a web browser
     5  package main
     6  
     7  import (
     8  	"bufio"
     9  	"encoding/base64"
    10  	"encoding/json"
    11  	"errors"
    12  	"fmt"
    13  	"io"
    14  	"os"
    15  	"strings"
    16  	"time"
    17  
    18  	"github.com/pion/randutil"
    19  	"github.com/pion/webrtc/v4"
    20  )
    21  
    22  func main() {
    23  	// Everything below is the Pion WebRTC API! Thanks for using it ❤️.
    24  
    25  	// Prepare the configuration
    26  	config := webrtc.Configuration{
    27  		ICEServers: []webrtc.ICEServer{
    28  			{
    29  				URLs: []string{"stun:stun.l.google.com:19302"},
    30  			},
    31  		},
    32  	}
    33  
    34  	// Create a new RTCPeerConnection
    35  	peerConnection, err := webrtc.NewPeerConnection(config)
    36  	if err != nil {
    37  		panic(err)
    38  	}
    39  	defer func() {
    40  		if cErr := peerConnection.Close(); cErr != nil {
    41  			fmt.Printf("cannot close peerConnection: %v\n", cErr)
    42  		}
    43  	}()
    44  
    45  	// Set the handler for Peer connection state
    46  	// This will notify you when the peer has connected/disconnected
    47  	peerConnection.OnConnectionStateChange(func(s webrtc.PeerConnectionState) {
    48  		fmt.Printf("Peer Connection State has changed: %s\n", s.String())
    49  
    50  		if s == webrtc.PeerConnectionStateFailed {
    51  			// Wait until PeerConnection has had no network activity for 30 seconds or another failure. It may be reconnected using an ICE Restart.
    52  			// Use webrtc.PeerConnectionStateDisconnected if you are interested in detecting faster timeout.
    53  			// Note that the PeerConnection may come back from PeerConnectionStateDisconnected.
    54  			fmt.Println("Peer Connection has gone to failed exiting")
    55  			os.Exit(0)
    56  		}
    57  
    58  		if s == webrtc.PeerConnectionStateClosed {
    59  			// PeerConnection was explicitly closed. This usually happens from a DTLS CloseNotify
    60  			fmt.Println("Peer Connection has gone to closed exiting")
    61  			os.Exit(0)
    62  		}
    63  	})
    64  
    65  	// Register data channel creation handling
    66  	peerConnection.OnDataChannel(func(d *webrtc.DataChannel) {
    67  		fmt.Printf("New DataChannel %s %d\n", d.Label(), d.ID())
    68  
    69  		// Register channel opening handling
    70  		d.OnOpen(func() {
    71  			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())
    72  
    73  			ticker := time.NewTicker(5 * time.Second)
    74  			defer ticker.Stop()
    75  			for range ticker.C {
    76  				message, sendErr := randutil.GenerateCryptoRandomString(15, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    77  				if sendErr != nil {
    78  					panic(sendErr)
    79  				}
    80  
    81  				// Send the message as text
    82  				fmt.Printf("Sending '%s'\n", message)
    83  				if sendErr = d.SendText(message); sendErr != nil {
    84  					panic(sendErr)
    85  				}
    86  			}
    87  		})
    88  
    89  		// Register text message handling
    90  		d.OnMessage(func(msg webrtc.DataChannelMessage) {
    91  			fmt.Printf("Message from DataChannel '%s': '%s'\n", d.Label(), string(msg.Data))
    92  		})
    93  	})
    94  
    95  	// Wait for the offer to be pasted
    96  	offer := webrtc.SessionDescription{}
    97  	decode(readUntilNewline(), &offer)
    98  
    99  	// Set the remote SessionDescription
   100  	err = peerConnection.SetRemoteDescription(offer)
   101  	if err != nil {
   102  		panic(err)
   103  	}
   104  
   105  	// Create an answer
   106  	answer, err := peerConnection.CreateAnswer(nil)
   107  	if err != nil {
   108  		panic(err)
   109  	}
   110  
   111  	// Create channel that is blocked until ICE Gathering is complete
   112  	gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
   113  
   114  	// Sets the LocalDescription, and starts our UDP listeners
   115  	err = peerConnection.SetLocalDescription(answer)
   116  	if err != nil {
   117  		panic(err)
   118  	}
   119  
   120  	// Block until ICE Gathering is complete, disabling trickle ICE
   121  	// we do this because we only can exchange one signaling message
   122  	// in a production application you should exchange ICE Candidates via OnICECandidate
   123  	<-gatherComplete
   124  
   125  	// Output the answer in base64 so we can paste it in browser
   126  	fmt.Println(encode(peerConnection.LocalDescription()))
   127  
   128  	// Block forever
   129  	select {}
   130  }
   131  
   132  // Read from stdin until we get a newline
   133  func readUntilNewline() (in string) {
   134  	var err error
   135  
   136  	r := bufio.NewReader(os.Stdin)
   137  	for {
   138  		in, err = r.ReadString('\n')
   139  		if err != nil && !errors.Is(err, io.EOF) {
   140  			panic(err)
   141  		}
   142  
   143  		if in = strings.TrimSpace(in); len(in) > 0 {
   144  			break
   145  		}
   146  	}
   147  
   148  	fmt.Println("")
   149  	return
   150  }
   151  
   152  // JSON encode + base64 a SessionDescription
   153  func encode(obj *webrtc.SessionDescription) string {
   154  	b, err := json.Marshal(obj)
   155  	if err != nil {
   156  		panic(err)
   157  	}
   158  
   159  	return base64.StdEncoding.EncodeToString(b)
   160  }
   161  
   162  // Decode a base64 and unmarshal JSON into a SessionDescription
   163  func decode(in string, obj *webrtc.SessionDescription) {
   164  	b, err := base64.StdEncoding.DecodeString(in)
   165  	if err != nil {
   166  		panic(err)
   167  	}
   168  
   169  	if err = json.Unmarshal(b, obj); err != nil {
   170  		panic(err)
   171  	}
   172  }