浏览器与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
邮箱:2919033008@qq.com
qq:2919033008