github => https://github.com/link1st/gowebsocket

文档: https://blog.csdn.net/m0_70556273/article/details/127306181

https://blog.csdn.net/u010750137/article/details/128439424

package main

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

//设置websocket
//CheckOrigin防止跨站点的请求伪造
var upGrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

//websocket实现
func ping(c *gin.Context) {
    //升级get请求为webSocket协议
    ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
    if err != nil {
        return
    }
    defer ws.Close() //返回前关闭
    for {
        //读取ws中的数据
        mt, message, err := ws.ReadMessage()
        if err != nil {
            break
        }
        //写入ws数据
        err = ws.WriteMessage(mt, message)
        if err != nil {
            break
        }
    }
}

func main() {
    r := gin.Default()
    r.GET("/ping", ping)
    r.Run(":12345")
}

使用melody三方库
github: https://github.com/olahol/melody

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/olahol/melody"
    "time"
)

func main() {
    r := gin.Default()
    m := melody.New()

    //访问地址:  ws://127.0.0.1:5001/ws
    r.GET("/ws", func(c *gin.Context) {
        m.HandleRequest(c.Writer, c.Request)
    })

    m.HandleMessage(func(s *melody.Session, msg []byte) {
        switch string(msg) {
        case "hello":
            s.Write([]byte("hi"))
        case "time":
            s.Write([]byte(time.Now().String()))
        case "exit":
            s.Write([]byte("Bye bye!"))
            s.Close()
        default:
            s.Write([]byte("Unknown Message"))
        }
    })

    r.Run(":5001")
}

goper
413 声望25 粉丝

go 后端开发