stratux/main/uibroadcast.go

68 wiersze
1.5 KiB
Go

2016-01-19 13:39:46 +00:00
/*
Copyright (c) 2015-2016 Christopher Young
2017-04-19 19:57:25 +00:00
Distributable under the terms of The "BSD New" License
2016-01-19 13:39:46 +00:00
that can be found in the LICENSE file, herein included
as part of this header.
uibroadcast.go: Helper functions for managementinterface - notification channels for update "subscriptions"
(used for weather and traffic websockets).
*/
package main
import (
2016-10-24 19:36:54 +00:00
"encoding/json"
"golang.org/x/net/websocket"
2015-11-10 22:27:06 +00:00
"sync"
2015-10-19 02:07:37 +00:00
"time"
)
type uibroadcaster struct {
2015-11-10 23:44:00 +00:00
sockets []*websocket.Conn
2015-11-10 22:49:44 +00:00
sockets_mu *sync.Mutex
2015-11-10 23:44:00 +00:00
messages chan []byte
}
func NewUIBroadcaster() *uibroadcaster {
ret := &uibroadcaster{
2015-11-10 22:27:06 +00:00
sockets: make([]*websocket.Conn, 0),
sockets_mu: &sync.Mutex{},
messages: make(chan []byte, 1024),
}
go ret.writer()
return ret
}
func (u *uibroadcaster) Send(msg []byte) {
u.messages <- msg
}
2016-10-24 19:36:54 +00:00
func (u *uibroadcaster) SendJSON(i interface{}) {
j, _ := json.Marshal(&i)
u.Send(j)
}
func (u *uibroadcaster) AddSocket(sock *websocket.Conn) {
2015-11-10 22:27:06 +00:00
u.sockets_mu.Lock()
u.sockets = append(u.sockets, sock)
2015-11-10 22:27:06 +00:00
u.sockets_mu.Unlock()
}
func (u *uibroadcaster) writer() {
for {
msg := <-u.messages
// Send to all.
p := make([]*websocket.Conn, 0) // Keep a list of the writeable sockets.
2015-11-10 22:27:06 +00:00
u.sockets_mu.Lock()
for _, sock := range u.sockets {
err := sock.SetWriteDeadline(time.Now().Add(time.Second))
_, err2 := sock.Write(msg)
if err == nil && err2 == nil {
p = append(p, sock)
}
}
u.sockets = p // Save the list of writeable sockets.
2015-11-10 22:27:06 +00:00
u.sockets_mu.Unlock()
}
}