-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.go
80 lines (66 loc) · 1.3 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
package main
import (
"encoding/json"
"io"
"log"
"net"
"sync"
msg "github.com/abdelq/lode-runner/message"
)
type client struct {
conn net.Conn
once sync.Once
out chan *msg.Message
}
func newClient(conn net.Conn) *client {
client := &client{conn: conn, out: make(chan *msg.Message, 1)}
// Listeners
go client.read()
go client.write()
log.Printf("New connection from %s", conn.RemoteAddr())
return client
}
func (c *client) close() {
c.once.Do(func() {
// Leave all joined rooms
rooms.Range(func(n, r interface{}) bool {
if _, ok := r.(*room).clients[c]; ok {
r.(*room).leave <- c
}
return true
})
//close(c.out)
c.conn.Close()
log.Printf("Closed connection from %s", c.conn.RemoteAddr())
})
}
func (c *client) read() {
defer c.close()
dec := json.NewDecoder(c.conn)
for {
message := new(message)
if err := dec.Decode(message); err != nil {
if err == io.EOF || err == io.ErrClosedPipe {
break
}
if _, ok := err.(net.Error); ok {
break
}
c.out <- msg.NewMessage("error", err.Error())
continue
}
go message.parse(c)
}
}
func (c *client) write() {
defer c.close()
enc := json.NewEncoder(c.conn)
for msg := range c.out {
if err := enc.Encode(msg); err != nil {
if _, ok := err.(net.Error); ok {
break
}
log.Println(err)
}
}
}