websocket是一種協(xié)議,用于在web應(yīng)用程序中建立實(shí)時(shí)缆蝉、雙向通信的通道掏呼。通過websocket可以實(shí)現(xiàn)server主動(dòng)向client端推送消息井佑,這個(gè)相較于傳統(tǒng)的輪詢和長(zhǎng)輪詢,可以顯著的減少對(duì)應(yīng)的網(wǎng)絡(luò)流量和延遲守呜。
這邊我主要介紹的是如何在golang中建立這樣的一個(gè)通道振愿,以下是簡(jiǎn)單的demo
一、環(huán)境依賴
1弛饭、采用gin框架搭建一個(gè)簡(jiǎn)單的工程
2冕末、下載github.com/gorilla/websocket依賴包
二、目錄結(jié)構(gòu)
目錄結(jié)構(gòu)如下
image.png
以下是每個(gè)文件對(duì)應(yīng)的代碼
服務(wù)端代碼
1侣颂、main.go
package main
import (
"github.com/gin-gonic/gin"
"pay/app"
)
func main() {
r := gin.Default() //創(chuàng)建gin
app.RegistRoute(r) //綁定路由
r.Run(":8001") //運(yùn)行綁定端口
}
2档桃、route.go
package app
import (
"github.com/gin-gonic/gin"
"pay/app/controller"
)
func RegistRoute(engine *gin.Engine) {
group := engine.Group("/index")
{
group.GET("/regist", controller.Index.Regist)
group.GET("/index", controller.Index.Index)
}
engine.LoadHTMLGlob("templates/*")
}
3、index.go
package controller
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net"
"net/http"
)
var Index = new(index)
type index struct {
}
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func (i *index) Index(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index.html", map[string]interface{}{
"title": "首頁",
})
}
func (i *index) Regist(ctx *gin.Context) {
conn, err := upGrader.Upgrade(ctx.Writer, ctx.Request, nil)
if err != nil {
fmt.Println("websocket error:", err)
return
}
//得到客戶的連接ip和端口
fmt.Println("client connect:", conn.RemoteAddr())
go i.Do(conn)
}
func (i *index) Do(conn *websocket.Conn) {
for {
//獲取到前端發(fā)送過來的websocket消息
contentType, message, err := conn.ReadMessage()
if err != nil {
//判斷是不是超時(shí)
if netErr, ok := err.(net.Error); ok {
if netErr.Timeout() {
fmt.Printf("ReadMessage timeout remote:%v\n", conn.RemoteAddr())
}
}
// 其他錯(cuò)誤憔晒,如果是 1001 和 1000藻肄,就不打印日志
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {
}
conn.Close()
//這邊必須return,因?yàn)榍岸说逆溄涌赡苣硞€(gè)時(shí)間段就斷開鏈接了拒担,要是沒有return嘹屯,會(huì)導(dǎo)致產(chǎn)生 repeated read on failed websocket connection報(bào)錯(cuò),而且也可以防止內(nèi)存泄露
return
}
fmt.Println(contentType)
fmt.Println(string(message))
//寫入ws
msg := []byte("我是server")
err = conn.WriteMessage(1, msg)
if err != nil {
fmt.Println("發(fā)生錯(cuò)誤了")
fmt.Println(err.Error())
}
}
}
前端代碼
index.html
hello
<button onclick="sendMsg()">發(fā)送消息給服務(wù)端</button>
<script>
var ws = new WebSocket("http://localhost:8001/index/regist")
ws.onopen = function (event){
console.log(event)
console.log("打開成功")
}
ws.onmessage = function (event){
console.log(event)
console.log("接收到消息:"+event.data)
}
ws.onclose = function (event){
console.log(event)
console.log("關(guān)閉")
}
function sendMsg(){
ws.send("hello server,I am client")
}
</script>
三、測(cè)試
瀏覽器訪問http://localhost:8001/index/index
1从撼、如下顯示打開成功州弟,代表前端和后端的websocket通信通道正式建立
image.png
2、當(dāng)點(diǎn)擊發(fā)送消息給服務(wù)端的時(shí)候,可以從瀏覽器看到對(duì)應(yīng)的消息交互
image.png
3婆翔、服務(wù)端也能看到對(duì)應(yīng)的前端消息拯杠,如下
image.png