-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.go
60 lines (50 loc) · 1.12 KB
/
socket.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
package main
import (
"github.com/gorilla/websocket"
)
func NewSocket(conn *websocket.Conn) *Socket {
return &Socket{
conn: conn,
output: make(chan string),
input: make(chan string),
err: make(chan bool),
}
}
type Socket struct {
// The websocket connection.
conn *websocket.Conn
output chan string
input chan string
err chan bool
}
func (s *Socket) Output() chan string { return s.output }
func (s *Socket) Input() chan string { return s.input }
func (s *Socket) Err() chan bool { return s.err }
func (s *Socket) Start() {
go s.writer()
go s.reader()
}
func (s *Socket) Terminate() {
s.conn.Close()
}
func (s *Socket) reader() {
for {
_, bytes, err := s.conn.ReadMessage()
if err != nil {
s.err <- true
break
}
s.input <- string(bytes)
}
s.conn.Close()
}
func (s *Socket) writer() {
for message := range s.output {
bytes := []byte(message)
err := s.conn.WriteMessage(websocket.TextMessage, bytes)
if err != nil {
break
}
}
s.conn.Close()
}