forked from redsift/rewebsocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket_test.go
115 lines (99 loc) · 2.2 KB
/
websocket_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
package rewebsocket
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gorilla/websocket"
)
func connect(url string, header http.Header) (*websocket.Conn, error) {
conn, _, err := websocket.DefaultDialer.Dial(url, header)
if err != nil {
return nil, err
}
return conn, err
}
func TestWebSocketReconnect(t *testing.T) {
srv := httptest.NewServer(echoer(t))
defer srv.Close()
wsURL := strings.Replace(srv.URL, "http", "ws", 1)
readCh := make(chan []byte)
var connectCount int
c := TextClient{
OnReadMessage: func(cancel chan struct{}, msg []byte) {
readCh <- msg
},
logln: t.Log,
}
err := c.Open(func(cancel chan struct{}) (*websocket.Conn, error) {
connectCount++
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
return nil, err
}
return conn, err
})
if err != nil {
t.Fatal("client dial:", err)
}
defer c.Close()
var receivedEcho bool
for i := 0; i < 10; i++ {
select {
case message := <-readCh:
t.Logf("client recv: %s", message)
receivedEcho = true
goto End
case <-time.After(200 * time.Millisecond):
t.Log("read timed out")
err = c.WriteTextMessage([]byte(`hello`))
if err != nil {
t.Log("client write:", err)
continue
}
t.Log("client write SUCCESS")
}
}
End:
if !receivedEcho {
t.Fatal("did not receive echo from server")
}
if connectCount != 4 {
t.Fatal("unexpected amount of connects", connectCount)
}
}
func echoer(t *testing.T) http.HandlerFunc {
var upgrader = websocket.Upgrader{}
var failureCounter int
return func(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
t.Log("server upgrade:", err)
return
}
defer c.Close()
failureCounter++
// fake connection issue the first three times
if failureCounter <= 3 {
return
}
for {
mt, message, err := c.ReadMessage()
if err != nil {
if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
t.Log("client disconnected")
break
}
t.Log("server read:", err)
break
}
t.Logf("server recv: %s", message)
err = c.WriteMessage(mt, message)
if err != nil {
t.Log("server write:", err)
break
}
}
}
}