forked from hootrhino/rulex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws_test.go
74 lines (64 loc) · 1.46 KB
/
ws_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
package test
import (
"net/url"
"os"
"os/signal"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/i4de/rulex/glogger"
)
func Test_WS(t *testing.T) {
ws()
}
func ws() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "ws", Host: "localhost:2580", Path: "/ws"}
glogger.GLogger.Printf("connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
glogger.GLogger.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
glogger.GLogger.Println("read:", err)
return
}
glogger.GLogger.Printf("Client recv: %s", message)
}
}()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
<-ticker.C
select {
case <-done:
ticker.Stop()
return
case t := <-ticker.C:
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
if err != nil {
glogger.GLogger.Println("write:", err)
return
}
case <-interrupt:
glogger.GLogger.Println("interrupt")
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
glogger.GLogger.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}