gin 和gorilla 写websocket 示例商业代码
时间: 2023-03-10 11:16:17 浏览: 129
答:使用 Gin 和 Gorilla 开发 WebSocket 应用程序的示例商业代码如下: package mainimport (
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}func main() {
r := gin.Default()
r.GET("/ws", func(c *gin.Context) {
ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
defer ws.Close()
for {
// Write
err := ws.WriteMessage(websocket.TextMessage, []byte("Hello Client!"))
if err != nil {
c.AbortWithError(500, err)
} // Read
_, msg, err := ws.ReadMessage()
if err != nil {
c.AbortWithError(500, err)
}
c.String(200, string(msg))
}
}) r.Run(":8080")
}
阅读全文