server.go
package main
import (
"github.com/labstack/echo/v4"
"golang.org/x/net/websocket"
)
func main() {
//20200727
e := echo.New()
e.GET("/ws", func(c echo.Context) error {
handler := websocket.Handler(func(conn *websocket.Conn) {
readString(conn)
conn.Write([]byte("ok"))
println("send client : ok")
})
handler.ServeHTTP(c.Response().Writer, c.Request())
return nil
})
e.Start(":11111")
}
func readString(conn *websocket.Conn) {
var msg = make([]byte, 1024)
read, err := conn.Read(msg)
if err != nil {
println(err)
}
println("from client : ", string(msg[:read]))
}
client_test.go
package main
import (
"encoding/json"
"golang.org/x/net/websocket"
"testing"
)
var wsurl = "ws://localhost:11111/ws"
var origin = "ws://localhost:11111"
func TestSend(t *testing.T) {
// 20200727
ws, err := websocket.Dial(wsurl, "", origin)
if err != nil {
t.Log(err)
}
m := make(map[string]string)
m["deviceId"] = "123"
marshal, _ := json.Marshal(m)
if err := websocket.Message.Send(ws, marshal); err != nil {
t.Log(err)
}
t.Log("send server : ", m)
data := make([]byte, 1024)
n, err := ws.Read(data)
if err != nil {
t.Error(err)
}
t.Log("form server : ", string(data[:n]))
}