This repository was archived by the owner on Mar 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathapp_test.go
132 lines (105 loc) · 2.17 KB
/
app_test.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
/**
@author:panliang
@data:2021/11/14
@note
**/
package tests
import (
"crypto/rand"
"flag"
"fmt"
"github.com/gorilla/websocket"
"im_app/config"
"im_app/pkg/jwt"
"log"
"math/big"
"sync"
"testing"
"time"
)
func init() {
config.Initialize()
}
var addr = flag.String("addr", "127.0.0.1:9502", "http service address")
type TestHandler interface {
Send(id int,msg []byte)
}
var ClientManager =ConnMap{
client: make(map[int]*Client),
}
type ConnMap struct {
client map[int]*Client
}
type Client struct {
Token string
Conn *websocket.Conn
Queue chan []byte
Mu sync.Mutex
}
var numbers = 50000
func TestApp(t *testing.T) {
for i := 1; i < numbers; i++ {
ClientManager.start(i)
}
fmt.Println("5w连接存储成功:")
for j := 1; j < numbers; j++ {
if conn,ok := ClientManager.client[j];ok{
time.Sleep(time.Microsecond*2)
wg.Add(1)
conn.Send(j)
}
}
wg.Wait()
}
func (c *ConnMap)start(i int) {
name := fmt.Sprintf("测试%d",i)
token := jwt.GenerateToken(int64(i), name, "test", "[email protected]", 1)
u := "ws://127.0.0.1:9502/core/connect?token="+token
fmt.Println(name)
conn, _, err := websocket.DefaultDialer.Dial(u, nil)
if err != nil {
log.Fatal("dial:", err,u)
}
mutexKey.Lock()
c.client[i]= &Client{Conn: conn,Token: token,Queue: make(chan []byte,40)}
mutexKey.Unlock()
go c.client[i].write() //执行
}
var mutexKey sync.Mutex
func (c *Client)write() {
// 关闭socket连接
defer c.Conn.Close()
for {
select {
case message, ok := <-c.Queue:
if !ok {
// 关闭
c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
c.Mu.Lock()
c.Conn.WriteMessage(websocket.TextMessage, message)
c.Mu.Unlock()
}
}
}
//消息推送
func (c *Client)Send(i int) {
t_id :=random()
data := fmt.Sprintf(`{"msg":"%s","from_id":%v,"to_id":%v,"status":0,"msg_type":%v,"channel_type":%v}`,
"test",i,t_id, 1,1)
//消息投递
c.Queue <- []byte(data)
c.Queue <- []byte(data)
c.Queue <- []byte(data)
c.Queue <- []byte(data)
c.Queue <- []byte(data)
}
func random() int {
max := big.NewInt(5000)
i, err := rand.Int(rand.Reader, max)
if err != nil {
log.Fatal("rand:", err)
}
return i.BitLen()
}