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)?