freifunkmanager/websocket/client.go

115 lines
2.0 KiB
Go
Raw Normal View History

2017-05-08 19:13:29 +02:00
package websocket
import (
"io"
"golang.org/x/net/websocket"
"github.com/FreifunkBremen/freifunkmanager/lib/log"
)
const channelBufSize = 100
type Client struct {
ip string
ws *websocket.Conn
ch chan *Message
writeQuit chan bool
readQuit chan bool
2017-05-08 19:13:29 +02:00
}
func NewClient(ip string, ws *websocket.Conn) *Client {
if ws == nil {
log.Log.Panic("ws cannot be nil")
2017-05-08 19:13:29 +02:00
}
return &Client{
ws: ws,
ch: make(chan *Message, channelBufSize),
writeQuit: make(chan bool),
readQuit: make(chan bool),
ip: ip,
2017-05-08 19:13:29 +02:00
}
}
func (c *Client) Write(msg *Message) {
select {
case c.ch <- msg:
default:
delete(clients, c.ip)
log.HTTP(c.ws.Request()).Error("client disconnected")
2017-05-08 19:13:29 +02:00
}
}
func (c *Client) Close() {
c.writeQuit <- true
c.readQuit <- true
log.HTTP(c.ws.Request()).Info("client disconnecting...")
}
// Listen Write and Read request via chanel
func (c *Client) Listen() {
go c.listenWrite()
c.allNodes()
c.listenRead()
2017-05-08 19:13:29 +02:00
}
func (c *Client) allNodes() {
for _, node := range nodes.List {
c.Write(&Message{Type: MessageTypeCurrentNode, Node: node})
2017-05-08 19:13:29 +02:00
}
for _, node := range nodes.ToUpdate {
c.Write(&Message{Type: MessageTypeUpdateNode, Node: node})
2017-05-08 19:13:29 +02:00
}
}
func (c *Client) handleMassage(msg *Message) {
switch msg.Type {
case MessageTypeUpdateNode:
nodes.UpdateNode(msg.Node)
}
2017-05-08 19:13:29 +02:00
}
// Listen write request via chanel
func (c *Client) listenWrite() {
for {
select {
case msg := <-c.ch:
websocket.JSON.Send(c.ws, msg)
case <-c.writeQuit:
close(c.ch)
close(c.writeQuit)
delete(clients, c.ip)
2017-05-08 19:13:29 +02:00
return
}
}
}
// Listen read request via chanel
func (c *Client) listenRead() {
for {
select {
case <-c.readQuit:
close(c.readQuit)
delete(clients, c.ip)
2017-05-08 19:13:29 +02:00
return
default:
var msg Message
err := websocket.JSON.Receive(c.ws, &msg)
if err == io.EOF {
close(c.readQuit)
c.writeQuit <- true
return
2017-05-08 19:13:29 +02:00
} else if err != nil {
log.HTTP(c.ws.Request()).Error(err)
} else {
c.handleMassage(&msg)
2017-05-08 19:13:29 +02:00
}
}
}
}