kopia lustrzana https://github.com/cyoung/stratux
Mutex for uibroadcaster.sockets.
rodzic
3777d5a7c0
commit
9691d47a75
|
@ -2,18 +2,21 @@ package main
|
|||
|
||||
import (
|
||||
"golang.org/x/net/websocket"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type uibroadcaster struct {
|
||||
sockets []*websocket.Conn
|
||||
messages chan []byte
|
||||
sockets []*websocket.Conn
|
||||
socket_mu *sync.Mutex
|
||||
messages chan []byte
|
||||
}
|
||||
|
||||
func NewUIBroadcaster() *uibroadcaster {
|
||||
ret := &uibroadcaster{
|
||||
sockets: make([]*websocket.Conn, 0),
|
||||
messages: make(chan []byte, 1024),
|
||||
sockets: make([]*websocket.Conn, 0),
|
||||
sockets_mu: &sync.Mutex{},
|
||||
messages: make(chan []byte, 1024),
|
||||
}
|
||||
go ret.writer()
|
||||
return ret
|
||||
|
@ -24,7 +27,9 @@ func (u *uibroadcaster) Send(msg []byte) {
|
|||
}
|
||||
|
||||
func (u *uibroadcaster) AddSocket(sock *websocket.Conn) {
|
||||
u.sockets_mu.Lock()
|
||||
u.sockets = append(u.sockets, sock)
|
||||
u.sockets_mu.Unlock()
|
||||
}
|
||||
|
||||
func (u *uibroadcaster) writer() {
|
||||
|
@ -32,6 +37,7 @@ func (u *uibroadcaster) writer() {
|
|||
msg := <-u.messages
|
||||
// Send to all.
|
||||
p := make([]*websocket.Conn, 0) // Keep a list of the writeable sockets.
|
||||
u.sockets_mu.Lock()
|
||||
for _, sock := range u.sockets {
|
||||
err := sock.SetWriteDeadline(time.Now().Add(time.Second))
|
||||
_, err2 := sock.Write(msg)
|
||||
|
@ -40,5 +46,6 @@ func (u *uibroadcaster) writer() {
|
|||
}
|
||||
}
|
||||
u.sockets = p // Save the list of writeable sockets.
|
||||
u.sockets_mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
|
Ładowanie…
Reference in New Issue