-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample.go
136 lines (119 loc) · 2.52 KB
/
example.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// Package websocket
package main
import (
"fmt"
"net/http"
"time"
"github.com/go-redis/redis/v8"
"github.com/assembly-hub/websocket"
"github.com/assembly-hub/websocket/multisub"
"github.com/assembly-hub/websocket/simplesub"
"github.com/assembly-hub/websocket/singlesub"
)
var (
rd *redis.Client
)
// SimpleGroupTest Demo
func SimpleGroupTest() {
// fmt.Println("Hello, Goutil!")
g := simplesub.NewManager()
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
err := g.AddGroup("test", w, r)
if err != nil {
fmt.Println(err)
}
})
go func() {
for {
time.Sleep(time.Second * 1)
err := g.SendMsg("test", "123")
if err != nil {
panic(err)
}
}
}()
}
// RedisGroupTest Demo
func RedisGroupTest() {
// label 每个建议不一样,防止数据干扰
g := multisub.NewManager(rd, "my_label")
// 设置自定义标签,防止冲突
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
err := g.AddGroup("test", w, r)
if err != nil {
fmt.Println(err)
}
})
go func() {
for {
time.Sleep(time.Second * 1)
err := g.SendMsg("test", "msg")
if err != nil {
fmt.Println(err.Error())
}
}
}()
}
// SingleRedisGroupTest Demo
func SingleRedisGroupTest() {
// label 每个建议不一样,防止数据干扰
g := singlesub.NewManager(rd, "my_label")
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
err := g.AddGroupWithExt("test", w, r, &websocket.GroupExtData{
CloseSendData: "123",
CloseCallback: func(data interface{}) {
fmt.Println(data)
},
})
if err != nil {
fmt.Println(err)
}
})
go func() {
for {
time.Sleep(time.Second * 1)
err := g.SendMsg("test", "test")
if err != nil {
return
}
}
}()
}
// SingleWSTest Demo
func SingleWSTest() {
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
cli, err := websocket.NewWS(w, r, nil)
if err != nil {
fmt.Println(err)
}
cli.SetDealMsg(func(msg []byte) []byte {
fmt.Println(msg)
return msg
})
go func(cli *websocket.Client) {
for {
time.Sleep(time.Second * 1)
cli.SendMsg("test")
}
}(cli)
})
}
func RunExample() {
opts := redis.Options{}
opts.Addr = "127.0.0.1:6379"
opts.DB = 0
rd = redis.NewClient(&opts)
defer rd.Close()
// 本地组
// SimpleGroupTest()
// 一个组一个redis发布
SingleRedisGroupTest()
// 所有组公用一个redis发布
// RedisGroupTest()
// 简单的ws链接
// SingleWSTest()
err := http.ListenAndServe(":8000", nil)
if err != nil {
panic(err)
}
}