dispatch/server/websocket.go

87 lines
1.2 KiB
Go
Raw Normal View History

2015-06-05 22:34:13 +00:00
package server
import (
"time"
2016-03-01 00:51:26 +00:00
"github.com/gorilla/websocket"
2018-05-25 21:54:36 +00:00
"github.com/mailru/easyjson"
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
}
2018-05-25 21:54:36 +00:00
err = c.writeJSON(res)
2015-06-05 22:34:13 +00:00
case <-ping:
2018-05-25 21:54:36 +00:00
err = c.writeJSON(WSResponse{Type: "ping"})
2015-06-05 22:34:13 +00:00
}
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 {
2018-05-25 21:54:36 +00:00
err := c.readJSON(&req)
2015-06-05 22:34:13 +00:00
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
}
2018-05-25 21:54:36 +00:00
func (c *wsConn) readJSON(v easyjson.Unmarshaler) error {
_, r, err := c.conn.NextReader()
if err != nil {
return err
}
return easyjson.UnmarshalFromReader(r, v)
}
func (c *wsConn) writeJSON(v easyjson.Marshaler) error {
w, err := c.conn.NextWriter(websocket.TextMessage)
if err != nil {
return err
}
_, err1 := easyjson.MarshalToWriter(v, w)
err2 := w.Close()
if err1 != nil {
return err1
}
return err2
}