我正在关注大猩猩提供的聊天示例。
我仍然可以解组发送的 json 数据。我应该在readPump()
:
func (c *ChatClient) readPump() {
defer func() {
c.hub.unregisterChan <- 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()
// =================MY CODE START=============
var comment Comment
err = c.conn.ReadJSON(comment)
if err != nil {
LogErr("readjson()", err)
break
}
err = json.Unmarshal(message, comment)
if err != nil {
LogErr("readjson()", err)
break
}
// =================MY CODE END=============
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
LogErr("IsUnexpectedCloseError()", err)
}
break
}
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
c.hub.broadcastChan <- message
}
}
或在writePump()
func (c *ChatClient) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
// CLOSE
if !ok {
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := c.conn.NextWriter(websocket.BinaryMessage)
if err != nil {
LogErr("c.conn.NextWriter", err)
return
}
LogErr() 方法不打印任何消息。完全迷失在这里。
慕尼黑5688855
相关分类