-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
93 lines (73 loc) · 1.57 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
88
89
90
91
92
93
package netgate
import (
"errors"
"strings"
"sync"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
type Client struct {
id string //unique id
conn *websocket.Conn //websocket connection
room *RoomInterface //room where client is
lock *sync.Mutex //lock
}
func newClient(conn *websocket.Conn) *Client {
return &Client{
id: strings.ReplaceAll(uuid.New().String(), "-", ""),
conn: conn,
room: nil,
lock: &sync.Mutex{},
}
}
func (c *Client) GetID() string {
return c.id
}
func (c *Client) GetRoom() *RoomInterface {
return c.room
}
func (c *Client) Send(data []byte) error {
c.lock.Lock()
defer c.lock.Unlock()
if c.conn == nil {
return errors.New("client is not connected")
}
err := c.conn.WriteMessage(websocket.BinaryMessage, data)
if err != nil {
return err
}
return nil
}
func (c *Client) Disconnect() error {
c.lock.Lock()
defer c.lock.Unlock()
if c.conn == nil {
return errors.New("client is not connected")
}
err := c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
return err
}
return c.close()
}
func (c *Client) close() error {
err := c.conn.Close()
if err != nil {
return err
}
c.conn = nil
return nil
}
func (c *Client) read() ([]byte, error) {
if c.conn == nil {
return nil, errors.New("client is not connected")
}
_, msg, err := c.conn.ReadMessage()
if err != nil {
if !websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
return nil, err
}
return nil, err
}
return msg, nil
}