fox/ws/ws_test.go
2025-05-29 20:30:18 +08:00

75 lines
1.2 KiB
Go

package ws
import (
"fmt"
"github.com/fox/fox/log"
"testing"
"time"
)
var (
serverAddr = ":8080"
addr = "localhost:8080"
)
func initLog() {
log.Open("test.Log", log.DebugL)
}
func wsServer() {
s := NewWsServer(serverAddr, func(conn IConn, data []byte) {
log.DebugF("服务端收到消息:%v", string(data))
_ = conn.SendMsg(data)
}, func(conn IConn) {
log.Debug(conn.Log("退出"))
})
s.Run()
}
type onFunc struct {
}
func (onFunc) OnMessage(msg []byte) error {
log.DebugF("收到消息,内容:%v", string(msg))
return nil
}
func wsClient() {
client, err := NewClient(fmt.Sprintf("ws://%v", addr), onFunc{})
if err != nil {
log.Fatal(err.Error())
return
}
defer client.Stop()
count := 1
client.Start()
msg := fmt.Sprintf("hell world %v", count)
// Log.Debug(fmt.Sprintf("%v", []byte(msg)))
client.SendMsg([]byte(msg))
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
count++
client.SendMsg([]byte(fmt.Sprintf("hell world %v", count)))
if count > 30 {
return
}
}
break
}
}
func TestWebsocket(t *testing.T) {
initLog()
wsServer()
wsClient()
// time.Sleep(60 * time.Second)
log.Debug("shutdown")
}