关于go:go-websocket-使用

43次阅读

共计 1216 个字符,预计需要花费 4 分钟才能阅读完成。

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")
}

正文完
 0