-
Notifications
You must be signed in to change notification settings - Fork 3
/
type_channel.go
105 lines (88 loc) · 2.67 KB
/
type_channel.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
94
95
96
97
98
99
100
101
102
103
104
105
package wsKit
import (
"context"
"fmt"
"github.com/gorilla/websocket"
"github.com/richelieu-yang/chimera/v3/src/component/web/push/pushKit"
"github.com/richelieu-yang/chimera/v3/src/compress/brotliKit"
"github.com/richelieu-yang/chimera/v3/src/compress/gzipKit"
"github.com/richelieu-yang/chimera/v3/src/time/timeKit"
"time"
)
var (
_ pushKit.Channel = &WsChannel{}
)
type WsChannel struct {
pushKit.BaseChannel
msgType *MessageType
conn *websocket.Conn
}
func (channel *WsChannel) Initialize() error {
if channel.PongInterval > 0 {
channel.Interval = timeKit.SetInterval(context.TODO(), func(t time.Time) {
if err := channel.Push(pushKit.PongData); err != nil {
pushKit.GetDefaultLogger().WithError(err).Error("Fail to pong.")
return
}
}, channel.PongInterval)
}
return nil
}
func (channel *WsChannel) Push(data []byte) error {
return channel.PushMessage(channel.msgType, data)
}
// PushMessage 推送消息给客户端.
/*
@param MessageType MessageTypeText || MessageTypeBinary
*/
func (channel *WsChannel) PushMessage(messageType *MessageType, data []byte) (err error) {
if messageType.gzipConfig != nil {
/* gzip压缩 */
data, err = gzipKit.Compress(data, gzipKit.WithLevel(messageType.gzipConfig.Level), gzipKit.WithCompressThreshold(messageType.gzipConfig.CompressThreshold))
if err != nil {
return err
}
} else if messageType.brotliConfig != nil {
/* brotli压缩 */
data, err = brotliKit.Compress(data, brotliKit.WithLevel(messageType.brotliConfig.Level), brotliKit.WithCompressThreshold(messageType.brotliConfig.CompressThreshold))
if err != nil {
return err
}
}
if channel.Closed {
return pushKit.ChannelClosedError
}
abortFlag := false
/* 写锁 */
channel.RWMutex.LockFunc(func() {
if channel.Closed {
err = pushKit.ChannelClosedError
abortFlag = true
return
}
err = channel.conn.WriteMessage(messageType.value, data)
})
if abortFlag {
return
}
if err != nil {
// Closed == true 的情况下,推送消息失败(基本上就是连接断开了)
closeInfo := fmt.Sprintf("Fail to push because of error(%s)", err.Error())
if channel.SetClosed() {
channel.GetCloseCh() <- closeInfo
}
}
return
}
// Close 后端主动关闭通道.
func (channel *WsChannel) Close(reason string) (err error) {
closeInfo := fmt.Sprintf("Closed by backend with reason(%s)", reason)
channel.Listeners.BeforeClosedByBackend(channel, closeInfo)
// Richelieu: 这里延迟3毫秒,以免: BeforeClosedByBackend()里面会向前端发消息,前端先触发onclose,再触发onmessage
time.Sleep(time.Millisecond * 3)
if channel.SetClosed() {
channel.GetCloseCh() <- closeInfo
err = channel.conn.Close()
}
return
}