-
Notifications
You must be signed in to change notification settings - Fork 3
/
type_channel.go
110 lines (91 loc) · 2.64 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
106
107
108
109
110
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/core/errorKit"
"github.com/richelieu-yang/chimera/v3/src/time/timeKit"
"time"
)
type WsChannel struct {
pushKit.BaseChannel
conn *websocket.Conn
messageType messageType
interval *timeKit.Interval
}
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
}
// Dispose 仅是释放资源,不会关闭通道(应当先关闭通道,再释放资源).
func (channel *WsChannel) Dispose() {
channel.interval.Stop()
channel.interval = nil
}
func (channel *WsChannel) Push(data []byte) error {
return channel.PushMessage(channel.messageType, data)
}
// PushMessage 推送消息给客户端.
/*
@param messageType MessageTypeText || MessageTypeBinary
*/
func (channel *WsChannel) PushMessage(messageType messageType, data []byte) (err error) {
switch messageType {
case MessageTypeText:
case MessageTypeBinary:
default:
err = errorKit.Newf("invalid message type(%d)", messageType)
return
}
if channel.Closed {
return pushKit.ChannelClosedError
}
// 是否推送失败?
failFlag := false
/* 写锁 */
channel.RWMutex.LockFunc(func() {
if channel.Closed {
err = pushKit.ChannelClosedError
return
}
err = channel.conn.WriteMessage(messageType.value, data)
failFlag = err != nil
})
if failFlag {
// 推送消息失败,基本上就是连接断开了
closeInfo := fmt.Sprintf("Fail to push because of error(%s)", err.Error())
if channel.SetClosed() {
channel.CloseCh <- 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.CloseCh <- closeInfo
err = channel.conn.Close()
}
return
}
func (channel *WsChannel) BindGroup(group string) {
pushKit.BindGroup(channel, group)
}
func (channel *WsChannel) BindUser(user string) {
pushKit.BindUser(channel, user)
}
func (channel *WsChannel) BindBsid(bsid string) {
pushKit.BindBsid(channel, bsid)
}