github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_unit_websocket_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package ghttp_test 8 9 import ( 10 "fmt" 11 "testing" 12 "time" 13 14 "github.com/gorilla/websocket" 15 16 "github.com/gogf/gf/frame/g" 17 "github.com/gogf/gf/net/ghttp" 18 "github.com/gogf/gf/test/gtest" 19 ) 20 21 func Test_WebSocket(t *testing.T) { 22 p, _ := ports.PopRand() 23 s := g.Server(p) 24 s.BindHandler("/ws", func(r *ghttp.Request) { 25 ws, err := r.WebSocket() 26 if err != nil { 27 r.Exit() 28 } 29 for { 30 msgType, msg, err := ws.ReadMessage() 31 if err != nil { 32 return 33 } 34 if err = ws.WriteMessage(msgType, msg); err != nil { 35 return 36 } 37 } 38 }) 39 s.SetPort(p) 40 s.SetDumpRouterMap(false) 41 s.Start() 42 defer s.Shutdown() 43 44 time.Sleep(100 * time.Millisecond) 45 gtest.C(t, func(t *gtest.T) { 46 conn, _, err := websocket.DefaultDialer.Dial(fmt.Sprintf("ws://127.0.0.1:%d/ws", p), nil) 47 t.Assert(err, nil) 48 defer conn.Close() 49 50 msg := []byte("hello") 51 err = conn.WriteMessage(websocket.TextMessage, msg) 52 t.Assert(err, nil) 53 54 mt, data, err := conn.ReadMessage() 55 t.Assert(err, nil) 56 t.Assert(mt, websocket.TextMessage) 57 t.Assert(data, msg) 58 }) 59 }