-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
84 lines (75 loc) · 1.45 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
package main
import (
"io"
stdLog "log"
"time"
"github.com/devfeel/dotweb"
"github.com/labstack/gommon/log"
)
type Client struct {
hub *Hub
closed chan struct{}
send chan string
ws *dotweb.WebSocket
}
func (c *Client) readLoop() {
defer func() {
c.hub.unregister <- c
c.ws.Conn.Close()
c.hub.wg.Done()
}()
for {
//判断是否为心跳信息
message, err := c.ws.ReadMessage()
if err != nil {
if err == io.EOF {
log.Warn("连接被客户端关闭了!")
c.closed <- struct{}{}
break
}
log.Errorf("error: %v", err)
break
}
switch message {
case "__PING__":
if err := c.ws.SendMessage("__PONG__"); err != nil {
log.Error(err)
return
}
case "__PONG__":
stdLog.Println(c.ws.Request().RemoteAddr, " is connected!")
default:
c.hub.broadcast <- message
}
}
}
func (c *Client) writeLoop() {
var ticker = time.NewTicker(5 * time.Second)
defer func() {
ticker.Stop()
c.ws.Conn.Close()
c.hub.wg.Done()
}()
for {
select {
case <-c.closed:
return
case message, ok := <-c.send:
if !ok {
c.ws.Conn.WriteClose(1000)
return
}
//将消息正式发送给客户端
err := c.ws.SendMessage(message)
if err != nil {
log.Error(err)
}
case <-ticker.C: //发送心跳信息
c.hub.broadcast <- "__PING__"
default:
time.Sleep(2 * time.Second)
//持续向客户端发广播
c.hub.broadcast <- "浙江温州江南皮革厂倒闭啦 !!!"
}
}
}