×

GO语言开发websocket服务

admin admin 发表于2022-03-31 11:57:22 浏览96 评论0

抢沙发发表评论

第一步引入相关模块

"github.com/gorilla/websocket"

第二步:创建相关服务

   update :=  websocket.Upgrader{
 ReadBufferSize:  1024,
 WriteBufferSize: 1024,
 CheckOrigin:     checkOrigin,
}


完整代码:

package main

import (
   "fmt"
   "github.com/gorilla/websocket"
   "log"
   "net/http"
)

func main() {

     update :=  websocket.Upgrader{
       ReadBufferSize:  1024,
       WriteBufferSize: 1024,
       CheckOrigin:     checkOrigin,
    }
   http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
         if true ==  websocket.IsWebSocketUpgrade(r){
           //是webscoket

           ws,err := update.Upgrade(w,r,w.Header())
          if err != nil{
             log.Println("请求出错")
          }
          defer ws.Close()
         for{
          var param = make(map[string]string)
          param["id"]="1"
          //ws.ReadJSON(&param).Error()
          n,msg ,_:= ws.ReadMessage()

          fmt.Println(n,string(msg))
          ws.WriteJSON(param)


       }




       }else{
         w.Write([]byte("当前不是WS请求"))
       }


   })
     log.Println("启动中")
   http.ListenAndServe("0.0.0.0:80",nil)
}
func checkOrigin(r *http.Request) bool {
   return true
}