【发布时间】:2017-09-08 18:00:51
【问题描述】:
我正在尝试修改 gorilla 聊天示例以向特定客户端发送消息而不是广播。首先,我将特定客户端存储在集线器中,与它的 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 添加了一个字段 Id int 以了解哪个客户端发送了消息
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
}
}
接下来要采取哪些步骤才能将消息发送到特定客户端而不是广播。
消息本身以 JSON 格式来自客户端,指定“to”指示要发送的对象和要发送的消息。
{"to":512,"message":"Hi there."}
【问题讨论】: