gin websocket

gin 中使用websocket功能

go get github.com/gorilla/websocket

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

engine.GET("/hello", func(context *gin.Context) {
  logrus.Infof("hello websocket")

  ws, err := upgrader.Upgrade(context.Writer, context.Request, nil)
  if err != nil {
    logrus.Errorf("websocket upgrade failed with err(%v)", err)
    return
  }

  go func() {
    for {
      t, message, err := ws.ReadMessage()
      if err != nil {
        logrus.Errorf("readmessage with err(%v)", err)
        break
      }
      logrus.Infof("type[%v]", t)

      // 写回去
      ws.WriteMessage(t, message)
    }

    ws.Close()
  }()
})

对应的前端js代码

<body>
    <button id="start">开始</button>
    <button id="stop">停止</button>
    
    <script src="../bootstrap/jquery-3.6.3.js"></script>
    <script>
        var ws;
        $(function() {
            console.log("websocket test start: " + document.location.hostname);
            ws = new WebSocket("ws://" + document.location.hostname + ":55555/hello")
            ws.binaryType = "arraybuffer"

            ws.onopen = function(e) {
                console.log("opened", ws.binaryType);
            }
            ws.close = function(e) {
                console.log("closed");
            }
            ws.onmessage = function(e) {
                console.log("recv: " + e.data);
            }

            var timer;
            $('#start').click(function() {
                timer = setInterval(function() {
                    let arr = new ArrayBuffer(12);
                    let b = new Uint8Array(arr);

                    for (let i=0; i<b.length; i++) {
                        b[i] = i*i
                    }

                    ws.send(b.buffer)
                    ws.send("hello");
                }, 1000)
            })

            $('#stop').click(function() {
                clearInterval(timer);
            })
        })
    </script>
</body>

posted on 2023-02-21 10:47  老张的巅峰  阅读(68)  评论(0)    收藏  举报

导航