Go Gin使用Websocket
2022-01-16 本文已影响0人
久百一
github地址:https://github.com/gin-gonic/gin
go get github.com/gin-gonic/gin
gorilla拥有很多类库,这次我们使用的是它的webSocket
go get github.com/gorilla/websocket
package main
import (
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
)
var upGrader = websocket.Upgrader{
CheckOrigin: func (r *http.Request) bool {
return true
},
}
//webSocket请求ping 返回pong
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
}
if string(message) == "ping" {
message = []byte("pong")
}
//写入ws数据
err = ws.WriteMessage(mt, message)
if err != nil {
break
}
}
}
func main() {
bindAddress := "localhost:2303"
r := gin.Default()
r.GET("/ping", ping)
r.Run(bindAddress)
}
前端js代码
<script>
var ws = new WebSocket("ws://localhost:2303/ping");
//连接打开时触发
ws.onopen = function(evt) {
console.log("Connection open ...");
ws.send("Hello WebSockets!");
};
//接收到消息时触发
ws.onmessage = function(evt) {
console.log("Received Message: " + evt.data);
};
//连接关闭时触发
ws.onclose = function(evt) {
console.log("Connection closed.");
};
</script>