github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/websocket/test/server_test.go (about)

     1  package test
     2  
     3  import (
     4  	"log"
     5  	"testing"
     6  
     7  	"github.com/isyscore/isc-gobase/server"
     8  	"github.com/isyscore/isc-gobase/websocket"
     9  )
    10  
    11  func TestWebSocketServer(t *testing.T) {
    12  	ws := websocket.NewWSServer(websocket.Config{
    13  		ReadBufferSize:  1024,
    14  		WriteBufferSize: 1024,
    15  	})
    16  	ws.OnConnection(handleConnection)
    17  	server.RegisterWebSocketRoute("/ws", ws)
    18  	server.StartServer()
    19  }
    20  
    21  func handleConnection(c websocket.Connection) {
    22  	log.Println("client connected,id=", c.ID())
    23  	_ = c.Write(1, []byte("welcome client"))
    24  	c.On("chat", func(msg string) {
    25  		log.Printf("%s sent: %s\n", c.Context().ClientIP(), msg)
    26  		_ = c.To(websocket.All).Emit("chat", msg)
    27  	})
    28  	c.OnMessage(func(msg []byte) {
    29  		log.Println("received msg:", string(msg))
    30  		_ = c.Write(1, []byte("hello aa"))
    31  		_ = c.To(websocket.All).Emit("chat", msg)
    32  	})
    33  	c.OnDisconnect(func() {
    34  		log.Println("client Disconnect,id=", c.ID())
    35  	})
    36  }