Skip to content

Instantly share code, notes, and snippets.

@chertov
Last active May 22, 2019 11:35
Show Gist options
  • Save chertov/8c00c7798fcb3673b5aa7d38e2789356 to your computer and use it in GitHub Desktop.
Save chertov/8c00c7798fcb3673b5aa7d38e2789356 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"github.com/pions/ice"
"log"
"strconv"
"time"
)
type Offer struct {
Frag string
Pwd string
Candidates []*ice.Candidate
}
var supportedNetworkTypes = []ice.NetworkType{
ice.NetworkTypeUDP4,
ice.NetworkTypeUDP6,
ice.NetworkTypeTCP4, // Not supported yet
ice.NetworkTypeTCP6, // Not supported yet
}
func agent(name string, controlling bool, local chan Offer, remote chan Offer) {
var config ice.AgentConfig
url, _ := ice.ParseURL( "stun:stun.l.google.com:19302")
config.Urls = []*ice.URL{url}
config.NetworkTypes = supportedNetworkTypes
a, err := ice.NewAgent(&config)
if err != nil { panic(name + "Error constructing ice.Agent") }
defer a.Close()
a.OnConnectionStateChange(func(state ice.ConnectionState) {
log.Println(name, " OnConnectionStateChange", state)
})
a.OnSelectedCandidatePairChange(func(cand1 *ice.Candidate, cand2 *ice.Candidate) {
log.Println(name, " OnSelectedCandidatePairChange", cand1, cand2)
})
frag, pwd := a.GetLocalUserCredentials()
log.Println(name, " frag: ", frag, " frag: ", pwd)
localCandidates, err := a.GetLocalCandidates()
log.Println(name, " localCandidates", localCandidates)
if err != nil { panic(name + " Error constructing ice.Agent") }
offer := Offer{frag, pwd, localCandidates}
log.Println(name, " offer", offer)
local <- offer
remoteOffer := <- remote
log.Println(name, " remoteOffer", remoteOffer)
for _, candidate := range remoteOffer.Candidates { a.AddRemoteCandidate(candidate) }
ctx := context.Background()
var conn *ice.Conn
if controlling {
conn, err = a.Accept(ctx, remoteOffer.Frag, remoteOffer.Pwd)
if err != nil { panic(name + " Accept err " + err.Error()) }
} else {
conn, err = a.Dial(ctx, remoteOffer.Frag, remoteOffer.Pwd)
if err != nil { panic(name + " Dial err " + err.Error()) }
}
go func() {
var buf [1024*15]byte
for {
len, err := conn.Read(buf[:])
if err != nil { panic(err) }
log.Println(name, "incoming: ", len, err, string(buf[:len]))
}
}()
i := uint64(0)
for {
testPayload := []byte("This is a test " + strconv.FormatUint(i, 10))
conn.Write(testPayload)
time.Sleep(time.Second*2)
i += 1
}
}
func main() {
chan1 := make(chan Offer, 100)
chan2 := make(chan Offer, 100)
go agent("a1", true, chan1, chan2)
go agent("a2", false, chan2, chan1)
for { time.Sleep(time.Second*1) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment