瀏覽器與go語言的websocket通訊
簡介
WebSocket是HTML5一種新的協議。顧名思義,它在伺服器和瀏覽器之間建立了全雙工通訊。
需求背景
區塊鏈測試系統web前端平臺需要動態接收後端傳送的狀態資訊改變一次測試session過程的狀態顯示,測試用例在執行後會返回一次執行的session,後端根據該session實時返回測試狀態。
思路過程:
1.找到go語言websocket官方文件github官方地址https://github.com/gorilla/websocket
2.git clone程式碼,執行官方用例教程server
3.前端使用h5的websocket服務訪問server
4.根據專案需求封裝介面
bug踩坑:
1.can't load package: package server: build constraints exclude all Go files in /home/zeng/go-websocket/src/server
去掉 // +build ignore 即可
2.Firefox 無法建立到 ws://localhost:8080/echo 伺服器的連線。
server配置跨域訪問
var upgrader = websocket.Upgrader{
// 解決跨域問題
CheckOrigin: func(r *http.Request) bool {
return true
},
}
前端主要程式碼:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<h1>WebSocket</h1>
<script>
var websocket = new WebSocket("ws://localhost:8080/echo");
websocket.onopen = function () {
session = "abcd"
websocket.send(session);
console.log(websocket.readyState)
}
websocket.onmessage = function (event) {
console.log(event.data);
websocket.close()
}
websocket.onclose = function() {
alert("連線已關閉...");
};
</script>
</body>
</html>
後端主要程式碼:
package main
import (
"SocketService"
"encoding/json"
"fmt"
"time"
)
type Test struct {
Id string
Data string
}
func main() {
url := "localhost:8080"
SocketService.Init(url)
time.Sleep(time.Second * 10)
err := SocketService.SendMessage("abc", []byte("zeng"))
if err != nil {
fmt.Println("1:", err)
}
t := Test{"Id", "Data"}
d, _ := json.Marshal(t)
session := "abcd"
SocketService.SendMessage(session, d)
if err != nil {
fmt.Println("2:", err)
}
time.Sleep(time.Second * 1000)
}
參考部落格:
https://blog.csdn.net/imliutao2/article/details/80838975
https://blog.csdn.net/wang_gongzi/article/details/82860427
demo傳送門:https://github.com/umbrellahusky/gowebsocket
郵箱:
qq:2919033008