»
(19)websocket
go语言实现websocket的方案有多种,具体可以到https://pkg.go.dev/search?q=websocket&m=package搜索对应的实现包。 这里要讲的是gorilla websocket的实现: 1)需要在beego的router中加入websocket的访问路径: beego.Router("/ws", &controllers.WebSocketController{}, "get,post:ServeHttp") 2)在WebSocketController中,实现请求具体的处理方法ServeHttp: type WebSocketController struct { beego.Controller } var upgrader = websocket.Upgrader{ HandshakeTimeout: 10 * time.Second, } // http请求,请求websocket服务,此方法处理WebSocket请求 func (c *WebSocketController) ServeWs() { token := c.GetString("token") clientId := getClientIdFromToken(token) //协议升级 ws, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil) if err != nil { println("ws conn failed", err.Error()) return } //启动一个goroutine协程 go serveClientGoRoutine(ws, clientId) } 3)goroutine协程处理对应的客户端的业务逻辑: func serveClientGoRoutine(ws *websocket.Conn, clientId string) { //解决socket关闭的情况 defer func(ws *websocket.Conn) { err := ws.Close() if err != nil { println("close ws conn error", err.Error()) } }(ws) //开始处理请求 for { var msg []byte msgType, msg, err := ws.ReadMessage() if err != nil { println("ws read message failed", err.Error()) return } if msgType == websocket.TextMessage { var msgJson WsJsonMsg json.Unmarshal(msg, &msgJson) println(msgJson.MsgType, msgJson.MsgCode, msgJson.MsgContent) msgJson.MsgContent = "echo " + msgJson.MsgContent var echoData []byte echoData, err = json.Marshal(msgJson) if err != nil { println("ws echo failed", err.Error()) continue } err = ws.WriteMessage(websocket.TextMessage, echoData) if err != nil { println("ws echo failed", err.Error()) continue } } } } 4)WebSocketController代码文件的import: import ( "encoding/json" beego "github.com/beego/beego/v2/server/web" "github.com/gorilla/websocket" "time" ) ————www.v-signon.com学习者共勉