ComunicRTCProxy/ws.go

106 lines
1.8 KiB
Go

// Websocket controller
//
// @author Pierre HUBERT
package main
import (
"encoding/json"
"log"
"os"
"os/signal"
"github.com/gorilla/websocket"
)
// WsMessage is a message from or to the api server
type WsMessage struct {
Title string `json:"title"`
CallHash string `json:"callHash"`
PeerID string `json:"peerId"`
Data interface{} `json:"data"`
}
var outMsgChan = make(chan interface{})
// Open websocket connection
func openWs(conf *Config) {
// Auto-close connection when the system request it
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := conf.getURL()
log.Printf("Connecting to %s", u.String())
// Connect to Websocket
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
// Wait for interrupt signal
go func() {
<-interrupt
c.Close()
}()
// Send outgoing messages
go func() {
for {
c.WriteJSON(<-outMsgChan)
}
}()
// Read remote messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Printf("WS Read error: %s", err.Error())
return
}
// Process incoming messages
// Decode JSON
var msg WsMessage
json.Unmarshal(message, &msg)
switch msg.Title {
// call configuration
case "config":
println("Got call configuration")
setCallConfig(msg.Data.(map[string]interface{}))
break
// Remote signal
case "signal":
onSignal(msg.CallHash, msg.PeerID, msg.Data.(map[string]interface{}))
break
default:
println("Received unkown message type!")
log.Printf("recv: %s", message)
break
}
}
}
/// Send a signal to the API
func sendSignal(callHash, peerID string, data interface{}) {
msg := WsMessage{
Title: "signal",
PeerID: peerID,
CallHash: callHash,
Data: data,
}
outMsgChan <- msg
}