gin框架实现websocket服务非常简单,只需要升级一下http请求,就可以实现了
比如下面的控制器部分代码
代码语言:javascript复制//包级变量,升级器
var upgrader = websocket.Upgrader{}
func init() {
//初始化
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
// 解决跨域问题
CheckOrigin: func(r *http.Request) bool {
return true
},
}
}
代码语言:javascript复制func VisitorWebsocketServer(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println("upgrade error:", err)
return
}
for {
//接受消息
var receive []byte
messageType, receive, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
log.Println(string(receive), messageType)
}
}
增加api路由
代码语言:javascript复制 wsGroup := engine.Group("/ws")
{
wsGroup.GET("/v2/visitor", middleware.Ipblack, wsV2.VisitorWebsocketServer)
}
前端连接访问就可以了
ws://xxxxxxxx/ws/v2/visitor