2015-06-05 22:34:13 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
type conn struct {
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
func newConn(ws *websocket.Conn) *conn {
|
|
|
|
return &conn{
|
|
|
|
conn: ws,
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *conn) send() {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *conn) recv() {
|
|
|
|
var req WSRequest
|
|
|
|
|
|
|
|
for {
|
|
|
|
err := c.conn.ReadJSON(&req)
|
|
|
|
if err != nil {
|
|
|
|
close(c.in)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
c.in <- req
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *conn) close() {
|
|
|
|
close(c.out)
|
|
|
|
}
|