dispatch/server/websocket.go

64 lines
867 B
Go
Raw Normal View History

2015-06-05 22:34:13 +00:00
package server
import (
"time"
2015-12-11 03:35:48 +00:00
"github.com/khlieng/dispatch/Godeps/_workspace/src/github.com/gorilla/websocket"
2015-06-05 22:34:13 +00:00
)
2015-06-16 22:46:58 +00:00
type wsConn struct {
2015-06-05 22:34:13 +00:00
conn *websocket.Conn
in chan WSRequest
2015-06-07 04:32:19 +00:00
out chan WSResponse
2015-06-05 22:34:13 +00:00
}
2015-06-16 22:46:58 +00:00
func newWSConn(conn *websocket.Conn) *wsConn {
return &wsConn{
conn: conn,
2015-06-05 22:34:13 +00:00
in: make(chan WSRequest, 32),
2015-06-07 04:32:19 +00:00
out: make(chan WSResponse, 32),
2015-06-05 22:34:13 +00:00
}
}
2015-06-16 22:46:58 +00:00
func (c *wsConn) send() {
2015-06-05 22:34:13 +00:00
var err error
ping := time.Tick(20 * time.Second)
for {
select {
2015-06-07 04:32:19 +00:00
case res, ok := <-c.out:
2015-06-05 22:34:13 +00:00
if !ok {
return
}
2015-06-07 04:32:19 +00:00
err = c.conn.WriteJSON(res)
2015-06-05 22:34:13 +00:00
case <-ping:
err = c.conn.WriteJSON(WSResponse{Type: "ping"})
}
if err != nil {
return
}
}
}
2015-06-16 22:46:58 +00:00
func (c *wsConn) recv() {
2015-06-05 22:34:13 +00:00
var req WSRequest
for {
err := c.conn.ReadJSON(&req)
if err != nil {
close(c.in)
return
}
c.in <- req
}
}
2015-06-16 22:46:58 +00:00
func (c *wsConn) close() {
2015-06-05 22:34:13 +00:00
close(c.out)
2015-06-16 22:46:58 +00:00
c.conn.Close()
2015-06-05 22:34:13 +00:00
}