go/websocket/client_test.go

115 lines
2.1 KiB
Go
Raw Normal View History

2015-05-05 03:45:01 +03:00
package websocket
import (
"net"
"net/http"
"net/url"
2018-05-14 09:06:05 +03:00
"sync"
2015-05-05 03:45:01 +03:00
"testing"
"time"
"github.com/gorilla/websocket"
)
func TestWSClient(t *testing.T) {
2018-05-14 09:06:05 +03:00
var wg sync.WaitGroup
wg.Add(1)
2015-05-05 03:45:01 +03:00
http.HandleFunc("/test/client", func(w http.ResponseWriter, r *http.Request) {
2018-05-14 09:06:05 +03:00
defer func() {
t.Log("server: wg.Done")
wg.Done()
}()
2015-05-05 03:45:01 +03:00
conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
if err != nil {
t.Fatal(err.Error())
}
2018-05-14 09:06:05 +03:00
t.Log("websocket.Upgrade")
2015-05-05 03:45:01 +03:00
2018-05-14 09:06:05 +03:00
conn.SetPingHandler(func(d string) error {
t.Log("receive from client: ", d)
conn.WriteMessage(websocket.PongMessage, []byte("server.Pong"))
return nil
})
2015-05-05 03:45:01 +03:00
2018-05-14 09:06:05 +03:00
msgType, msg, err := conn.ReadMessage()
2015-05-05 03:45:01 +03:00
if err != nil {
t.Fatal(err.Error())
}
if msgType != websocket.TextMessage {
t.Fatal("invalid msg type", msgType)
}
2018-05-14 09:06:05 +03:00
err = conn.WriteMessage(websocket.TextMessage, msg)
2015-05-05 03:45:01 +03:00
if err != nil {
t.Fatal(err.Error())
}
msgType, msg, err = conn.ReadMessage()
if err != nil {
t.Fatal(err.Error())
}
2018-05-14 09:06:05 +03:00
if msgType != websocket.TextMessage {
2015-05-05 03:45:01 +03:00
t.Fatal("invalid msg type", msgType)
}
2018-05-14 09:06:05 +03:00
conn.WriteMessage(websocket.PongMessage, []byte("server.Pong"))
2015-05-05 03:45:01 +03:00
})
go http.ListenAndServe(":65500", nil)
time.Sleep(time.Second * 1)
conn, err := net.Dial("tcp", "127.0.0.1:65500")
if err != nil {
t.Fatal(err.Error())
}
2018-05-14 09:06:05 +03:00
ws, _, err := NewClient(conn, &url.URL{Scheme: "ws", Host: "127.0.0.1:65501", Path: "/test/client"}, nil)
2015-05-05 03:45:01 +03:00
if err != nil {
t.Fatal(err.Error())
}
payload := make([]byte, 4*1024)
for i := 0; i < 4*1024; i++ {
payload[i] = 'x'
}
2018-05-14 09:06:05 +03:00
err = ws.WriteString(payload)
if err != nil {
t.Fatal(err.Error())
}
2015-05-05 03:45:01 +03:00
2018-05-14 09:06:05 +03:00
msgType, msg, err := ws.ReadMessage()
2015-05-05 03:45:01 +03:00
if err != nil {
t.Fatal(err.Error())
}
if msgType != TextMessage {
t.Fatal("invalid msg type", msgType)
}
if string(msg) != string(payload) {
t.Fatal("invalid msg", string(msg))
}
//test ping
2018-05-14 09:06:05 +03:00
err = ws.Ping([]byte("client.Ping"))
if err != nil {
t.Fatal(err.Error())
}
2015-05-05 03:45:01 +03:00
msgType, msg, err = ws.ReadMessage()
if err != nil {
t.Fatal(err.Error())
}
if msgType != PongMessage {
t.Fatal("invalid msg type", msgType)
}
2018-05-14 09:06:05 +03:00
ws.WriteMessage(websocket.TextMessage, []byte("done"))
// ws.Close()
wg.Wait()
2015-05-05 03:45:01 +03:00
}