go实现持久websocket推送及定时cron服务代码
代码语言:golang
所属分类:其他
代码描述:go实现持久websocket推送及定时服务代码,通过api进行通讯,支持cron定时服务。
代码标签: go 持久websocket 推送 定时 cron 服务 代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
// main.go package main import ( "context" "database/sql" "encoding/json" "errors" "log" "net/http" "os" "strings" "sync" "time" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/gorilla/websocket" _ "github.com/mattn/go-sqlite3" "github.com/robfig/cron/v3" ) // --- WebSocket ConnectionManager --- var upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true // Allow all connections }, } type ConnectionManager struct { // RWMutex is better here since sending messages (read-lock) is more frequent than connecting/disconnecting (write-lock). mu sync.RWMutex activeConnections map[string]*websocket.Conn } func NewConnectionManager() *ConnectionManager { return &ConnectionManager{ activeConnections: make(map[string]*websocket.Conn), } } func (m *ConnectionManager) Connect(ws *websocket.Conn) string { m.mu.Lock() defer m.mu.Unlock() clientID := uuid.New().String() m.activeConnections[clientID] = ws log.Printf("New client connected: %s", clientID) return clientID } func (m *ConnectionManager) Reconnect(clientID string, ws *websocket.Conn) string { m.mu.Lock() defer m.mu.Unlock() // If a previous connection existed, it will be replaced. m.activeConnections[clientID] = ws log.Printf("Client reconnected: %s", clientID) return clientID } func (m *ConnectionManager) Disconnect(clientID string) { m.mu.Lock() defer m.mu.Unlock() if _, ok := m.activeConnections[clientID]; ok { delete(m.activeConnections, clientID) log.Printf("Client disconnected: %s", clientID) } } type PushMessage struct { Type string `json:"type"` Data interface{} `json:"data"` } func (m *ConnectionManager) SendJSONToClients(data interface{}, cli.........完整代码请登录后点击上方下载按钮下载查看
网友评论0