Reputation: 45
I am new to Golang, I am trying to a create a WebSocket server which will broadcast messages to the connected clients. The messages here will be generated from the server side(by creating a default client).
Here is my client.go
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
new_chan := make(chan string)
//defer new_chan.Stop()
go func() {
for {
new_chan <- "my message"
}
}()
hub := newHub()
go hub.run()
client := &Client{hub: hub, ws: c, send: make(chan []byte, 256)}
for {
select {
case <-done:
return
case t := <-new_chan:
err := c.WriteMessage(websocket.TextMessage, []byte(t))
if err != nil {
log.Println("write:", err)
return
}
log.Printf(t)
client.hub.broadcast <- bytes.TrimSpace(bytes.Replace([]byte(t), newline, space, -1))
}
}
this function will generate the messages and try to broadcast to other clients.
server.go will add the clients to the hub
func echo(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
hub := newHub()
go hub.run()
client := &Client{hub: hub, ws: c, send: make(chan []byte, 256)}
client.hub.register <- client
go client.writePump()
writePump() here will listen to the client.send channel and broadcast messages Now the connected client's hub is different is from the hub of the client at the server. So when I try to send messages, I am not receiving anything. How can I make it belong to the same hub(context)?
Upvotes: 1
Views: 1581
Reputation: 120951
It looks like you are starting from the Gorilla chat example. In that example, use hub.broadcast <- message
to broadcast a message to all clients where hub
is the *Hub
created in main()
.
There's no need to create a client connection to send message originated from the server.
Here's a modified version of the main() that broadcasts "hello" to all clients every second:
func broadcast(hub *Hub) {
m := []byte("hello")
for range time.NewTicker(time.Second).C {
hub.broadcast <- m
}
}
func main() {
flag.Parse()
hub := newHub()
go hub.run()
go broadcast(hub)
http.HandleFunc("/", serveHome)
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
serveWs(hub, w, r)
})
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Upvotes: 1