Go 的 WebSocket 框架:Melody
Melody 是一個 Go 語言的微型 WebSocket 框架,基于 github.com/gorilla/websocket 開發,主要特性:
-
接口簡單易用,類似 net/http 或者 Gin
-
提供給所有廣播以及給選擇連接會話廣播的簡單途徑
-
消息緩沖對并發寫是安全的
-
可自動處理 ping/pong 和會話超時
一個簡單的實例:
代碼:
package main
import (
"github.com/olahol/melody"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
m := melody.New()
r.GET("/", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "index.html")
})
r.GET("/channel/:name", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "chan.html")
})
r.GET("/channel/:name/ws", func(c *gin.Context) {
m.HandleRequest(c.Writer, c.Request)
})
m.HandleMessage(func(s *melody.Session, msg []byte) {
m.BroadcastFilter(msg, func(q *melody.Session) bool {
return q.Request.URL.Path == s.Request.URL.Path
})
})
r.Run(":5000")
} 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
