ComunicRTCProxy/ws.go

76 lines
1.2 KiB
Go
Raw Normal View History

2020-04-10 07:43:14 +00:00
// Websocket controller
//
// @author Pierre HUBERT
package main
import (
2020-04-10 08:38:21 +00:00
"encoding/json"
2020-04-10 07:43:14 +00:00
"log"
2020-04-10 08:14:16 +00:00
"os"
"os/signal"
2020-04-10 07:43:14 +00:00
"github.com/gorilla/websocket"
)
2020-04-10 08:38:21 +00:00
// WsMessage is a message from or to the api server
type WsMessage struct {
2020-04-11 06:34:59 +00:00
Title string
CallHash string
PeerID string
Data interface{}
2020-04-10 08:38:21 +00:00
}
2020-04-10 07:43:14 +00:00
// Open websocket connection
func openWs(conf *Config) {
2020-04-10 08:14:16 +00:00
// Auto-close connection when the system request it
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
2020-04-10 07:43:14 +00:00
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()
2020-04-10 08:14:16 +00:00
// Wait for interrupt signal
go func() {
<-interrupt
c.Close()
}()
2020-04-10 07:43:14 +00:00
// Read remote messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Printf("WS Read error: %s", err.Error())
return
}
2020-04-10 08:38:21 +00:00
// Process incoming messages
2020-04-10 07:43:14 +00:00
log.Printf("recv: %s", message)
2020-04-10 08:38:21 +00:00
// 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
}
2020-04-10 07:43:14 +00:00
}
}