Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"crypto/tls"
"fmt"
"log"
"net"
"time"
"github.com/pion/logging"
"github.com/pion/turn"
)
const (
host = "MY_TURN_HOST"
port = 443
user = "MY_TURN_USER"
password = "MY_TURN_PASSWORD" //nolint
)
// createAllocation creates an allocation on the remote server
func createAllocation() net.PacketConn {
conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", host, port), &tls.Config{InsecureSkipVerify: true}) //nolint (ignore InsecureSkipVerify)
if err != nil {
panic(err)
}
client, err := turn.NewClient(&turn.ClientConfig{
TURNServerAddr: fmt.Sprintf("%s:%d", host, port),
STUNServerAddr: fmt.Sprintf("%s:%d", host, port),
Conn: turn.NewSTUNConn(conn),
Username: user,
Password: password,
LoggerFactory: logging.NewDefaultLoggerFactory(),
})
if err != nil {
panic(err)
}
if err = client.Listen(); err != nil {
panic(err)
}
allocation, err := client.Allocate()
if err != nil {
panic(err)
}
return allocation
}
// dataLoop writes to LocalAddr of a net.PacketConn, using another one
// it also may read from the writing net.PacketConn if requested
func dataLoop(src, dst net.PacketConn, alsoRead bool) {
if alsoRead {
go func() {
buf := make([]byte, 1500)
for {
n, _, err := src.ReadFrom(buf)
if err != nil {
panic(err)
}
fmt.Println(string(buf[:n]))
}
}()
}
for {
msg := time.Now().Format(time.RFC3339Nano)
if _, err := src.WriteTo([]byte(msg), src.LocalAddr()); err != nil {
panic(err)
}
time.Sleep(500 * time.Millisecond)
}
}
func main() {
writeAllocation := createAllocation()
log.Printf("relayed-address=%s", writeAllocation.LocalAddr().String())
dataLoop(writeAllocation, writeAllocation, true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.