go+gin+websocket实现轮询
2021-01-20 本文已影响0人
五岁小孩
<center><font size="5">go+gin+webSocket实现轮询</font></center>
js[^webSocket实时获取系统时间]
//获取当前项目访问的域名地址
var wsUrl = "ws://" + window.location.host + "/common/getSysDate";
//webSocket重新连接次数
let wsReConnectCount = 5;
$(function () {
//连接webSocket 获取系统时间
console.log("页面启动完成后加载......");
getSysDate(wsUrl);
});
function getSysDate(url) {
//判断当前浏览器是否支持
if ("WebSocket" in window && typeof WebSocket != 'undefined') {
//连接
let ws = new WebSocket(url);
//连接成功
ws.onopen = function () {
console.log("ws 连接成功......")
//ws.send("发送消息")
};
//接收消息
ws.onmessage = function (evt) {
let data = evt.data;
//console.log("ws 接受消息date=", JSON.parse(data).SysDate);
//console.log("ws 接受消息week=", JSON.parse(data).SysWeek);
//console.log("ws 接受消息time=", JSON.parse(data).SysTime);
//修改页面
$(".sysClock .sysDate").text(JSON.parse(data).SysDate);
$(".sysClock .sysWeek").text(JSON.parse(data).SysWeek);
$(".sysClock .sysTime").text(JSON.parse(data).SysTime);
};
//连接关闭
ws.onclose = function () {
console.log("ws 连接关闭")
};
//连接关闭或者失败 5秒后重新连接
ws.onerror = function (ev) {
console.log("webSocket 连接失败:", ev);
if (wsReConnectCount > 0) {
setTimeout(function () {
console.log("webSocket 第" + wsReConnectCount + "次重新连接");
getSysDate(wsUrl);
wsReConnectCount--;
}, 3000);
} else {
alert("系统时间更新失失败,WebSocket 连接超时");
}
}
} else {
alert("您的浏览器不支持WebSocket通信,建议使用火狐浏览器或者谷歌浏览器");
}
}
go
router
//--WebSocket 系统时间--
router.GET("/common/getSysDate", common.SysDateGetService)
service
package service
import (
"github.com/gorilla/websocket"
"time"
)
//webSocket 轮询获取系统时间
func SysDateGetService(c *gin.Context) {
ws, errByWs := upgrader.Upgrade(c.Writer, c.Request, nil)
if errByWs != nil {
logs.Error("Get system date connect webSocket error:%v", errByWs.Error())
return
}
logs.Debug("Get system date: webSocket connect success.....")
//返回时间
go func() {
for {
errByWsWriteJson := ws.WriteJSON(gin.H{
"SysDate": time.Now().Format("2006-01-02"),
"SysWeek": TPFunWeekMsgChange(GetAdminUserLang(c), time.Now().Weekday().String()),
"SysTime": time.Now().Format("15:04"),
})
if errByWsWriteJson != nil {
logs.Debug("webSocket WriteJson return SysDate error:%v", errByWsWriteJson.Error())
}
logs.Debug("webSocket WriteJson return success......")
//time.Sleep(time.Duration(10) * time.Second)
//休眠时间=60秒-当前秒数=经过多少秒后进入下一分钟
time.Sleep(time.Duration(60-time.Now().Second()) * time.Second)
}
}()
}