Gin 是用Go 编写的一个Web 应用框架,对比其它主流的同类框架,他有更好的性能和更快的路由
安装
go get github.com/gin-gonic/gin
gorilla, A fast, well-tested and widely used WebSocket implementation for Go.
安装
go get github.com/gorilla/websocket
服务器端代码(Gin参考教程:https://github.com/gin-gonic/gin#quick-start, https://www.tizi365.com/archives/244.html,gorilla教程參考https://godoc.org/github.com/gorilla/websocket)
package main
import (
"github.com/gorilla/websocket"
"net/http"
"github.com/gin-gonic/gin"
"fmt"
)
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 {
mt, message, err := ws.ReadMessage()
if err != nil {
break
}
fmt.Println(string(message))
err = ws.WriteMessage(mt, message)
if err != nil {
break
}
}
}
func main() {
bindAddress := "127.0.0.1:8090"
r := gin.Default()
r.GET("/ping", ping)
r.Run(bindAddress)
}
前端代码(前端websocket教程参考:https://www.ruanyifeng.com/blog/2017/05/websocket.html), 打开控制台,在控制台,查看输出
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
var ws = new WebSocket("ws://127.0.0.1:8090/ping");
//连接打开时触发
ws.onopen = function(evt) {
id = setInterval(function () {
ws.send("Hello WebSockets!")
console.log("Connection open ...");
}, 1000)
};
//接收到消息时触发
ws.onmessage = function(evt) {
console.log("Received Message: " + evt.data);
};
//连接关闭时触发
ws.onclose = function(evt) {
clearInterval(id)
console.log("Connection closed.");
};
</script>
</html>