-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
57 lines (47 loc) · 966 Bytes
/
connection.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
package topic_sockets
import (
"net/http"
)
type connection struct {
Sink chan TopicEvent
transport *transport
unregister chan<- *connection
}
func NewClient(w http.ResponseWriter, r *http.Request, onReceive chan<- clientTopicEvent, unregister chan<- *connection) *connection {
conn := &connection{
Sink: make(chan TopicEvent, 256),
transport: NewTransport(w, r),
unregister: unregister,
}
go conn.read(onReceive)
go conn.write()
return conn
}
func (c *connection) read(onReceive chan<- clientTopicEvent) {
defer c.close()
for {
event, ok := c.transport.receiveEvent()
if ok {
onReceive <- clientTopicEvent{
Client: c,
TopicEvent: event,
}
}
}
}
func (c *connection) write() {
defer c.close()
for {
event, ok := <-c.Sink
if !ok {
c.transport.close()
return
}
go c.transport.sendEvent(event)
}
}
func (c *connection) close() {
close(c.Sink)
c.transport.close()
c.unregister <- c
}