dongsha1544
2018-10-19 08:09 阅读 106
已采纳

Golang WebSocket数据不正确

I'm using x.net.websocket to read data from a websocket. The data is relatively large. When I read it, I can't read it completely, so it is cut off. Is there any way to solve it?

func receiveWebsocket(ws *websocket.Conn) error {
    for {
        var msg = make([]byte, 1024*1024) // 1024kb
        m, err := ws.Read(msg) 
        if err != nil {
            log15.Error("ws read error", "error", err)
            return err
        }
        fmt.Println("length ---",m,  string(msg))
        response := string(msg[:m])
        assignmentWebsocket(response)
    }
}

According to the log, the m value is always 4092, even if msg is very large.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dounianluo0086 dounianluo0086 2018-10-19 11:38

    First call always reads less than 4KB, and for security reasons the length is limited, if you want to increase, set:

    ws.MaxPayloadBytes = xxxx
    

    From the second call your msg will be filled.

    If you want to read the whole message in a single call,do:

    msg, err := ioutil.ReadAll(ws)
    
    点赞 评论 复制链接分享

相关推荐