-
Notifications
You must be signed in to change notification settings - Fork 26
/
client.go
87 lines (78 loc) · 1.73 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
r "github.com/dancannon/gorethink"
"github.com/gorilla/websocket"
"log"
)
type FindHandler func(string) (Handler, bool)
type Client struct {
send chan Message
socket *websocket.Conn
findHandler FindHandler
session *r.Session
stopChannels map[int]chan bool
id string
userName string
}
func (c *Client) NewStopChannel(stopKey int) chan bool {
c.StopForKey(stopKey)
stop := make(chan bool)
c.stopChannels[stopKey] = stop
return stop
}
func (c *Client) StopForKey(key int) {
if ch, found := c.stopChannels[key]; found {
ch <- true
delete(c.stopChannels, key)
}
}
func (client *Client) Read() {
var message Message
for {
if err := client.socket.ReadJSON(&message); err != nil {
break
}
if handler, found := client.findHandler(message.Name); found {
handler(client, message.Data)
}
}
client.socket.Close()
}
func (client *Client) Write() {
for msg := range client.send {
if err := client.socket.WriteJSON(msg); err != nil {
break
}
}
client.socket.Close()
}
func (c *Client) Close() {
for _, ch := range c.stopChannels {
ch <- true
}
close(c.send)
// delete user
r.Table("user").Get(c.id).Delete().Exec(c.session)
}
func NewClient(socket *websocket.Conn, findHandler FindHandler,
session *r.Session) *Client {
var user User
user.Name = "anonymous"
res, err := r.Table("user").Insert(user).RunWrite(session)
if err != nil {
log.Println(err.Error())
}
var id string
if len(res.GeneratedKeys) > 0 {
id = res.GeneratedKeys[0]
}
return &Client{
send: make(chan Message),
socket: socket,
findHandler: findHandler,
session: session,
stopChannels: make(map[int]chan bool),
id: id,
userName: user.Name,
}
}