github.com/pion/webrtc/v3@v3.2.24/examples/ice-restart/main.go (about) 1 // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly> 2 // SPDX-License-Identifier: MIT 3 4 // ice-restart demonstrates Pion WebRTC's ICE Restart abilities. 5 package main 6 7 import ( 8 "encoding/json" 9 "fmt" 10 "net/http" 11 "time" 12 13 "github.com/pion/webrtc/v3" 14 ) 15 16 var peerConnection *webrtc.PeerConnection //nolint 17 18 func doSignaling(w http.ResponseWriter, r *http.Request) { 19 var err error 20 21 if peerConnection == nil { 22 if peerConnection, err = webrtc.NewPeerConnection(webrtc.Configuration{}); err != nil { 23 panic(err) 24 } 25 26 // Set the handler for ICE connection state 27 // This will notify you when the peer has connected/disconnected 28 peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) { 29 fmt.Printf("ICE Connection State has changed: %s\n", connectionState.String()) 30 }) 31 32 // Send the current time via a DataChannel to the remote peer every 3 seconds 33 peerConnection.OnDataChannel(func(d *webrtc.DataChannel) { 34 d.OnOpen(func() { 35 for range time.Tick(time.Second * 3) { 36 if err = d.SendText(time.Now().String()); err != nil { 37 panic(err) 38 } 39 } 40 }) 41 }) 42 } 43 44 var offer webrtc.SessionDescription 45 if err = json.NewDecoder(r.Body).Decode(&offer); err != nil { 46 panic(err) 47 } 48 49 if err = peerConnection.SetRemoteDescription(offer); err != nil { 50 panic(err) 51 } 52 53 // Create channel that is blocked until ICE Gathering is complete 54 gatherComplete := webrtc.GatheringCompletePromise(peerConnection) 55 56 answer, err := peerConnection.CreateAnswer(nil) 57 if err != nil { 58 panic(err) 59 } else if err = peerConnection.SetLocalDescription(answer); err != nil { 60 panic(err) 61 } 62 63 // Block until ICE Gathering is complete, disabling trickle ICE 64 // we do this because we only can exchange one signaling message 65 // in a production application you should exchange ICE Candidates via OnICECandidate 66 <-gatherComplete 67 68 response, err := json.Marshal(*peerConnection.LocalDescription()) 69 if err != nil { 70 panic(err) 71 } 72 73 w.Header().Set("Content-Type", "application/json") 74 if _, err := w.Write(response); err != nil { 75 panic(err) 76 } 77 } 78 79 func main() { 80 http.Handle("/", http.FileServer(http.Dir("."))) 81 http.HandleFunc("/doSignaling", doSignaling) 82 83 fmt.Println("Open http://localhost:8080 to access this demo") 84 // nolint: gosec 85 panic(http.ListenAndServe(":8080", nil)) 86 }