浏览器 websocket 在发送 flatbuffer 的字节时发出 "Could not decode a text frame as UTF-8"

Browser websocket emit "Could not decode a text frame as UTF-8" when send flatbuffer's bytes

我使用以下函数将字节编码为 utf-8

func convrtToUTF8(origin []byte) []byte {
    byteReader := bytes.NewReader(origin)
    reader, _ := charset.NewReaderLabel("utf-8", byteReader)
    strBytes, _ = ioutil.ReadAll(reader)
    return strBytes
}

如何将 strByte 转换为原点?

详情,

原始字节来自 flatbuffers' builder.FinishedBytes() 我必须将它转换为 utf-8 字节以用于 websocket 连接(因为浏览器发出类似失败的错误:无法将文本框架解码为 UTF-8)

您提供的代码似乎从 UTF-8 转换为 UTF-8:

NewReaderLabel returns a reader that converts from the specified charset to UTF-8. It uses Lookup to find the encoding that corresponds to label, and returns an error if Lookup returns nil. Source: GoDoc

您没有检查返回的错误,但将任意二进制文件解码为 UTF-8 编码文本肯定会产生错误。

更重要的是,你想发送二进制数据,不要像文本一样将其编码为 UTF-8。要通过 websocket 发送,请将数据保持为二进制:

Data frames (e.g., non-control frames) are identified by opcodes where the most significant bit of the opcode is 0. Currently defined opcodes for data frames include 0x1 (Text), 0x2 (Binary). Opcodes 0x3-0x7 are reserved for further non-control frames yet to be defined.

来源:RFC 6455

例如,如果您使用 github.com/gorilla/websocket,您应该从 websocket read/write 使用 BinaryMessage 作为 messageType 参数。

The WebSocket protocol distinguishes between text and binary data messages. Text messages are interpreted as UTF-8 encoded text. The interpretation of binary messages is left to the application.

This package uses the TextMessage and BinaryMessage integer constants to identify the two data message types. The ReadMessage and NextReader methods return the type of the received message. The messageType argument to the WriteMessage and NextWriter methods specifies the type of a sent message.

来源:GoDoc