I'm trying to modify the gorilla chat example to to send a message to a specific client instead of broadcast. First I'm storing the specific client in the hub against it's Id.
Hub.go
type Hub struct {
Clients map[int]*Client // Changed this piece to store id (int)
Broadcast chan []byte
Register chan *Client
Unregister chan *Client
}
func (h *Hub) Run() {
for {
select {
case client := <-h.Register:
fmt.Println("hub client register")
h.Clients[client.Id] = client
case client := <-h.Unregister:
fmt.Println("hub client Unregister")
fmt.Println(h.Clients[client.Id])
if h.Clients[client.Id] != nil {
delete(h.Clients, client.Id)
close(client.Send)
}
case message := <-h.Broadcast:
fmt.Println("to send to a specific client", string(message))
}
}
}
Client
I've added a field Id int to Client to know which client has sent a message
type Client struct {
Hub *Hub
Conn *websocket.Conn
Send chan []byte
Id int // Id of the client,
}
func (c *Client) readPump() {
defer func() {
c.Hub.Unregister <- c
c.Conn.Close()
}()
c.Conn.SetReadLimit(maxMessageSize)
c.Conn.SetReadDeadline(time.Now().Add(pongWait))
c.Conn.SetPongHandler(func(string) error { c.Conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, message, err := c.Conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
log.Printf("error: %v", err)
}
break
}
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
fmt.Println("client read message", string(message), "from", c.Id)
// {"to":512,"message":"Hi there."}
c.Hub.Broadcast <- message
}
}
What are the next steps to take to be able to send the message to a specific client instead of broadcasting.
the message itself is coming as JSON from the client specifying 'to' indicating who to send and what message to send.
{"to":512,"message":"Hi there."}