-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
86 lines (77 loc) · 1.52 KB
/
client.go
File metadata and controls
86 lines (77 loc) · 1.52 KB
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
package websockets
import (
"fmt"
"github.com/gorilla/websocket"
)
type Client struct {
Id string
Send chan []byte
IsServer bool
CloseCallBack func()
groups map[string]*Manager
Server *Server
socket *websocket.Conn
}
func Init(id string, server *Server, conn *websocket.Conn) *Client {
client := &Client{
Id: id,
Send: make(chan []byte),
IsServer: true,
Server: server,
socket: conn,
}
go client.Write()
go client.Read()
return client
}
// Write: Send a message to the client
func (c *Client) Write() {
defer func() {
c.IsServer = false
c.socket.Close()
}()
for {
select {
case message, ok := <-c.Send:
if !ok {
c.socket.WriteMessage(websocket.CloseMessage, []byte{})
return
}
err := c.socket.WriteMessage(websocket.TextMessage, message)
if err != nil {
return
}
}
}
}
// Read: Process messages sent by the client
func (c *Client) Read() {
defer func() {
if err := recover(); err != nil {
// 记录日志 并且做对应的回调 @todo
fmt.Println("im recover", err)
go c.Read()
} else {
// 用户正常退出
c.IsServer = false
c.socket.Close()
}
}()
for {
_, message, err := c.socket.ReadMessage()
if err != nil {
return
}
err = c.Server.Protocol.Receive(c, message)
if err != nil {
return
}
}
}
func (c *Client)ToOne(toId string, msg interface{}) bool {
//c.Server.Protocol.
return true
}
func (c *Client)ToGroup(groupId string, msg interface{}) bool {
return true
}