github.com/gogf/gf/v2@v2.7.4/net/ghttp/ghttp_z_unit_feature_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/v2/frame/g"
    17  	"github.com/gogf/gf/v2/net/ghttp"
    18  	"github.com/gogf/gf/v2/test/gtest"
    19  	"github.com/gogf/gf/v2/util/guid"
    20  )
    21  
    22  func Test_WebSocket(t *testing.T) {
    23  	s := g.Server(guid.S())
    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.SetDumpRouterMap(false)
    40  	s.Start()
    41  	defer s.Shutdown()
    42  
    43  	time.Sleep(100 * time.Millisecond)
    44  	gtest.C(t, func(t *gtest.T) {
    45  		conn, _, err := websocket.DefaultDialer.Dial(fmt.Sprintf(
    46  			"ws://127.0.0.1:%d/ws", s.GetListenedPort(),
    47  		), nil)
    48  		t.AssertNil(err)
    49  		defer conn.Close()
    50  
    51  		msg := []byte("hello")
    52  		err = conn.WriteMessage(websocket.TextMessage, msg)
    53  		t.AssertNil(err)
    54  
    55  		mt, data, err := conn.ReadMessage()
    56  		t.AssertNil(err)
    57  		t.Assert(mt, websocket.TextMessage)
    58  		t.Assert(data, msg)
    59  	})
    60  }