Ai
2 Star 5 Fork 0

SillyMan/Ping多个主机的Web版本

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ws.go 2.27 KB
一键复制 编辑 原始数据 按行查看 历史
SillyMan 提交于 2021-01-07 21:48 +08:00 . first commit
package api
import (
"sync"
"time"
"gitee.com/sillyman/mixlog"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
"github.com/satori/go.uuid"
"gitee.com/sillyman/PingHostsWebView/models"
"gitee.com/sillyman/PingHostsWebView/modules/db"
)
var (
wsUpgrader = websocket.Upgrader{}
wsBroLatestPingSummariesConns = make(map[string]*websocket.Conn)
wsBroLatestPingSummariesConnsMutex = new(sync.Mutex)
wsBroLatestPingSummariesOnce = new(sync.Once)
)
// WsBroLatestPingSummaries 通过websocket广播最新的 pinger 结果
func WsBroLatestPingSummaries(c echo.Context) error {
wsConn, err := wsUpgrader.Upgrade(c.Response(), c.Request(), nil)
if err != nil {
return newHttpErrServer(err)
}
defer func() {
if wsConn != nil {
wsConn.Close()
}
}()
clientUUID := uuid.NewV4().String()
wsBroLatestPingSummariesConns[clientUUID] = wsConn
wsBroLatestPingSummariesOnce.Do(broLatestPingSummaries)
for {
if _, _, err := wsConn.ReadMessage(); err != nil { // 接收客户端的消息,但是不做任何处理
wsBroLatestPingSummariesConnsMutex.Lock()
delete(wsBroLatestPingSummariesConns, clientUUID)
wsBroLatestPingSummariesConnsMutex.Unlock()
break
}
}
return nil
}
// broLatestPingSummaries 一秒广播一次
func broLatestPingSummaries() {
t := time.NewTicker(time.Second)
for range t.C {
if len(wsBroLatestPingSummariesConns) == 0 {
wsBroLatestPingSummariesOnce = new(sync.Once)
break
}
latestNews := make([]models.PingSummary, 0, 128)
// 读取 2 秒更新的所有记录
dbConn := db.MustObtainMainDB()
if err := dbConn.Where("updated_at > ?", time.Now().Add(-2*time.Second)).Find(&latestNews).Error; err != nil {
mixlog.Fatalf("读数据库失败", err)
}
db.ReleaseMainDB()
wsBroLatestPingSummariesConnsMutex.Lock()
for clientUUID, wsConn := range wsBroLatestPingSummariesConns {
if wsConn == nil {
delete(wsBroLatestPingSummariesConns, clientUUID)
continue
}
if err := wsConn.WriteJSON(latestNews); err != nil {
// 浏览器断开了连接,通常是浏览器执行了 F5 刷新,导致 ws 中断了,但是浏览器又重新创建了新的连接。
delete(wsBroLatestPingSummariesConns, clientUUID)
}
}
wsBroLatestPingSummariesConnsMutex.Unlock()
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/sillyman/PingHostsWebView.git
git@gitee.com:sillyman/PingHostsWebView.git
sillyman
PingHostsWebView
Ping多个主机的Web版本
11e63cd92578

搜索帮助