Skip to content

Instantly share code, notes, and snippets.

@Sean-Der
Created October 7, 2019 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sean-Der/0fac80f8aa0ff9a76ad8daa24b9ed43d to your computer and use it in GitHub Desktop.
Save Sean-Der/0fac80f8aa0ff9a76ad8daa24b9ed43d to your computer and use it in GitHub Desktop.
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