gpt4 book ai didi

go - 浏览器WebSocket发送FlatBuffer的字节时发出 “Could not decode a text frame as UTF-8”

转载 作者:行者123 更新时间:2023-12-01 21:23:20 30 4
gpt4 key购买 nike

我使用以下功能将字节编码为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。要通过网络套接字发送,请将您的数据保留为二进制:

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,则应使用 BinaryMessage作为 messageType参数从Websocket读取/写入。

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

关于go - 浏览器WebSocket发送FlatBuffer的字节时发出 “Could not decode a text frame as UTF-8”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58987537/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com