Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

go - Sending Websocket messages to new clients

I am creating a chat API using Go and Gorilla websocket. I would like my users to receive the last 10 messages on establishing a websocket connection. However I can't find a simple way to do that. I would just like to send every message from my messages array to the new client. Is there a simple way to edit my code without hubs? Here is my code:

package messenger

import (
    "../config"
    "fmt"
    "github.com/go-chi/chi"
    "github.com/gorilla/websocket"
    log "github.com/sirupsen/logrus"
    "net/http"
)

func InitRouter() http.Handler {
    r := chi.NewRouter()
    r.Get("/", getWebsocket)
    return r
}

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

var messages = []Message{}

// Configure the upgrader
var upgrader = websocket.Upgrader{}

func getWebsocket(w http.ResponseWriter, r *http.Request) {
    // Upgrade initial GET request to a websocket
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Fatal(err)
    }
    // Make sure we close the connection when the function returns
    defer ws.Close()

    // Register our new client
    clients[ws] = true

    for {
        var msg Message
        // Read in a new message as JSON and map it to a Message object
        err := ws.ReadJSON(&msg)
        if err != nil {
            log.Printf("error: %v", err)
            delete(clients, ws)
            break
        }
        // Send the newly received message to the broadcast channel
        broadcast <- msg
        saveMessage(msg)
    }
}

func HandleMessages() {
    for {
        // Grab the next message from the broadcast channel
        msg := <-broadcast
        // Send it out to every client that is currently connected
        for client := range clients {
            err := client.WriteJSON(msg)
            if err != nil {
                log.Printf("error: %v", err)
                client.Close()
                delete(clients, client)
            }
        }
    }
}

func saveMessage(m Message) {
    if len(messages) >= config.Conf.MessageAmount {
        messages = messages[1:]
    }
    messages = append(messages, m)
    fmt.Println(messages)
}
question from:https://stackoverflow.com/questions/65857152/sending-websocket-messages-to-new-clients

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay looks like I did it. I just created a new function and called it fromgetWebsocket function passing the newly created Websocket. Here is the new function:

func serveInitialMessages(ws *websocket.Conn) {
for _, m := range messages {
    fmt.Println(m)
    err := ws.WriteJSON(m)
    if err != nil {
        fmt.Println(err)
    }
}

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...