golang 單點推送

zhangyumingtfr發表於2017-11-13

我想問一下後臺的單點推送怎麼做啊,是篩選連線,找到正確的連線然後推送嗎??求大神指點,這是我寫的廣播

package main

import (
    "github.com/gorilla/websocket"
    "log"
    "fmt"
    "net/http"
    "time"
)

var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan Message)

var upgrader = websocket.Upgrader{}
var chananel = make(chan string)//資料chan

type Message struct {
    Message string `json:"message"`
}
//有插入資料的時候就去資料庫
func hu(w http.ResponseWriter, r *http.Request) {
    chananel <- "aksjhdfkjahsdkjfhkj"
}

func main() {
    fs := http.FileServer(http.Dir("."))
    http.Handle("/", fs)
    http.HandleFunc("/o", hu)
    http.HandleFunc("/ws", handleConnections)
    go handleMessages()
    err := http.ListenAndServe(":8000", nil)
    if err != nil {
        log.Println(err.Error())
    }
}

//註冊成為 websocket
func handleConnections(w http.ResponseWriter, r *http.Request) {
    //獲取引數
    ws, err := upgrader.Upgrade(w, r, nil)
    defer ws.Close()
    if err != nil {
        log.Println(err.Error())
    }
    defer ws.Close()

    clients[ws] = true
    for {
        s := <-chananel
        msg := Message{Message: "資料" + time.Now().Format("2006-01-02 15:04:05") + s}
        broadcast <- msg
    }
}

//廣播傳送至頁面
func handleMessages() {
    for {
        msg := <-broadcast
        fmt.Println(clients)
        for client := range clients {
            err := client.WriteJSON(msg)
            if err != nil {
                log.Println(err.Error())
                client.Close()
                delete(clients, client)
            }
        }
    }
}
更多原創文章乾貨分享,請關注公眾號
  • golang 單點推送
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章