go语言websocket(gin-gonic+Gorilla)

首先使用gin创建一个http服务

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {

    r := gin.Default()
    r.LoadHTMLFiles("index.html")
    r.GET("/", func(c *gin.Context) {
        c.HTML(200, "index.html", nil)
    })

    r.Run("localhost:12312")
}

使用到了一个index.html模板,用来做客户端测试websocket的,仅作为演示用

安装gorilla

go get github.com/gorilla/websocket

修改main.go

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/gorilla/websocket"
)

var wsupgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func wshandler(w http.ResponseWriter, r *http.Request) {
    conn, err := wsupgrader.Upgrade(w, r, nil)
    if err != nil {
        fmt.Println("Failed to set websocket upgrade: %+v", err)
        return
    }

    for {
        t, msg, err := conn.ReadMessage()
        if err != nil {
            break
        }
        conn.WriteMessage(t, msg)
    }
}

func main() {

    r := gin.Default()

    //websocket 请求使用 wshandler函数处理
    r.GET("/ws", func(c *gin.Context) {
        wshandler(c.Writer, c.Request)
    })    

    r.LoadHTMLFiles("index.html")
    r.GET("/", func(c *gin.Context) {
        c.HTML(200, "index.html", nil)
    })

    r.Run("localhost:12312")
}

index.html 文件

<html>
  <head>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  </head>

  <body>
    <h3>WebSocket Go</h3>
    <pre id="output"></pre>

    <script>
      url = 'ws://localhost:12312/ws';
      c = new WebSocket(url);
      
      send = function(data){
        $("#output").append((new Date())+ " ==> "+data+"\n")
        c.send(data)
      }

      c.onmessage = function(msg){
        $("#output").append((new Date())+ " <== "+msg.data+"\n")
        console.log(msg)
      }

      c.onopen = function(){
        setInterval( 
          function(){ send("ping") }
        , 1000 )
      }
    </script>

  </body>
</html>

效果图:

输入图片说明

转载于:https://my.oschina.net/cxz001/blog/1581938

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值