-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn_test.go
99 lines (86 loc) · 1.65 KB
/
conn_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
package pool
import (
"HelloGo/basic/body"
"context"
"fmt"
"net"
"os"
"testing"
"time"
)
var OPT = &Option{
addr: "0.0.0.0:3000",
size: 3,
readTimeout: 3 * time.Second,
dialTimeout: 3 * time.Second,
keepAlive: 1 * time.Second,
}
func createConn(opt *Option) *Conn {
c, err := NewConn(opt)
if err != nil {
panic(err)
}
return c
}
func TestSendMsg(t *testing.T) {
c := createConn(OPT)
msg := &body.Message{Uid: "pixel-1", Val: "pixelpig!"}
rec, err := c.Send(context.Background(), msg)
if err != nil {
t.Error(err)
} else {
t.Logf("rec1: %+v", <-rec)
}
//msg.Val = "another pig!"
//rec2, err := c.SendInPool(context.Background(), msg)
//if err != nil {
// t.Error(err)
//} else {
// t.Logf("rec2: %+v", <-rec2)
//}
// timeout judgment
rec3, err := c.Send(context.Background(), msg)
if err == nil {
select {
case resp := <-rec3:
t.Logf("rec3: %+v", resp)
return
case <-time.After(time.Second * 1):
t.Error("Wait for resp timeout!")
return
}
} else {
t.Error(err)
}
t.Log("finished")
}
func TestAliveCheck(t *testing.T) {
conn, err := net.Dial("tcp", "127.0.0.1:3000")
if err != nil {
fmt.Println("dial failed:", err)
os.Exit(1)
}
defer conn.Close()
buffer := make([]byte, 512)
tcp, ok := conn.(*net.TCPConn)
if !ok {
return
}
if err := tcp.SetKeepAlive(true); err != nil {
t.Error(err)
return
}
// 30s之后开启状态检测
if err = tcp.SetKeepAlivePeriod(30 * time.Second); err != nil {
return
}
for {
n, err := tcp.Read(buffer)
if err != nil {
fmt.Println("Read failed:", err)
time.Sleep(1)
continue
}
fmt.Println("count:", n, "msg:", string(buffer))
}
}