github.com/godaddy-x/freego@v1.0.156/ws_server_test.go (about)

     1  package main
     2  
     3  import (
     4  	"github.com/godaddy-x/freego/node"
     5  	"github.com/godaddy-x/freego/utils"
     6  	"github.com/godaddy-x/freego/utils/jwt"
     7  	"testing"
     8  	"time"
     9  )
    10  
    11  type MsgReply struct {
    12  	Id   string      `json:"id"`
    13  	Ack  bool        `json:"ack"`
    14  	Type string      `json:"type"`
    15  	Data interface{} `json:"data"`
    16  }
    17  
    18  func TestWsServer(t *testing.T) {
    19  	server := node.WsServer{}
    20  	server.Debug = true
    21  	server.AddJwtConfig(jwt.JwtConfig{
    22  		TokenTyp: jwt.JWT,
    23  		TokenAlg: jwt.HS256,
    24  		TokenKey: "123456" + utils.CreateLocalSecretKey(12, 45, 23, 60, 58, 30),
    25  		TokenExp: jwt.TWO_WEEK,
    26  	})
    27  	server.NewPool(30, 1500, 20, 30)
    28  	handle := func(ctx *node.Context, message []byte) (interface{}, error) {
    29  		result := map[string]interface{}{}
    30  		if err := utils.JsonUnmarshal(message, &result); err != nil {
    31  			return nil, err
    32  		}
    33  		result["subject"] = ctx.Subject.GetSub()
    34  		//fmt.Println("receive ack:", result)
    35  		return nil, nil
    36  	}
    37  	server.AddRouter("/websocket", handle, nil)
    38  	go func() {
    39  		for {
    40  			reply := MsgReply{Id: utils.NextSID(), Type: "transfer", Data: "我爱中国"}
    41  			server.SendMessage(&reply, "1756510920302919681", "APP")
    42  			time.Sleep(5 * time.Second)
    43  		}
    44  	}()
    45  	server.StartWebsocket(":6060")
    46  }