dongsha1544 2018-10-19 08:09
浏览 187
已采纳

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 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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?