-
Notifications
You must be signed in to change notification settings - Fork 0
/
relay_test.go
113 lines (90 loc) · 1.92 KB
/
relay_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
package localrelay
import (
"io"
"net"
"sync"
"testing"
"time"
)
func TestConnPoolBasic(t *testing.T) {
conns := []net.Conn{}
connAmount := 50
relay := New("test-relay", "127.0.0.1:23838", "127.0.0.1:23838", io.Discard)
for i := 0; i < connAmount; i++ {
conn := &net.TCPConn{}
conns = append(conns, conn)
relay.storeConn(conn)
}
for i := 0; i < connAmount; i++ {
relay.popConn(conns[i])
}
if len(relay.connPool) != 0 {
t.Fatal("connPool is not empty")
}
}
func TestConnPool(t *testing.T) {
// create channel to receive errors from another goroutine
errCh := make(chan error)
go startTCPServer(errCh)
// wait for error or nil error indicating server launched fine
if err := <-errCh; err != nil {
t.Fatal(err)
}
relay := New("test-relay", "127.0.0.1:23838", "127.0.0.1:23838", io.Discard)
wg := sync.WaitGroup{}
// open 10 conns and append to the conn pool
for i := 0; i < 10; i++ {
wg.Add(1)
conn, err := net.Dial("tcp", "127.0.0.1:23838")
if err != nil {
t.Fatal(err)
}
relay.storeConn(conn)
// handle conn
go func(conn net.Conn, i int) {
for {
time.Sleep(time.Millisecond * (10 * time.Duration(i)))
_, err := conn.Write([]byte("test"))
if err != nil {
relay.popConn(conn)
for _, c := range relay.connPool {
if c.Conn == conn {
t.Fatal("correct conn was not removed")
}
}
wg.Done()
return
}
}
}(conn, i)
}
wg.Wait()
}
func startTCPServer(errCh chan error) {
l, err := net.Listen("tcp", ":23838")
if err != nil {
errCh <- err
return
}
errCh <- nil
for {
conn, err := l.Accept()
if err != nil {
continue
}
// handle conn with echo server
go func(conn net.Conn) {
for i := 0; i <= 5; i++ {
buf := make([]byte, 1048)
n, err := conn.Read(buf)
if err != nil {
conn.Close()
return
}
conn.Write(buf[:n])
}
// close conn after 5 messages
conn.Close()
}(conn)
}
}