-
Notifications
You must be signed in to change notification settings - Fork 2
/
connection.go
44 lines (37 loc) · 852 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
package main
import (
"strconv"
"github.com/gorilla/websocket"
)
// UserConnection represents user ws-connection and his UID
type UserConnection struct {
UID int
ws *websocket.Conn
}
// NewUserConnection constructor for UserConnection
func NewUserConnection(ws *websocket.Conn) *UserConnection {
return &UserConnection{ws: ws}
}
// Send method deliver message on websocket
func (u *UserConnection) Send(m Message) {
u.ws.WriteMessage(websocket.TextMessage, []byte(m.Message))
}
// Listen method listens ws-connection and tries to get user UID
func (u *UserConnection) Listen() {
defer func() {
u.ws.Close()
registry.Unregister(u)
}()
for {
_, message, err := u.ws.ReadMessage()
if err != nil {
break
}
uid, err := strconv.Atoi(string(message))
if err != nil {
continue
}
u.UID = uid
registry.Register(u)
}
}