3

我正在使用 golang 开发一个简单的聊天服务器和客户端。我在阅读来自 net.Conn 的消息时遇到了一些问题。到目前为止,这就是我一直在做的事情:

bufio.NewReader(conn).ReadString('\n')

由于用户按下回车键发送消息,我只需要阅读直到'\n'。但我现在正在研究加密,当在客户端和服务器之间发送公钥时,密钥有时包含'\n',这使得很难获得整个密钥。我只是想知道如何阅读整个消息而不是停留在特定字符上。谢谢!

4

1 回答 1

8

发送二进制数据的一个简单选项是使用长度前缀。将数据大小编码为 32 位大端整数,然后读取该数据量。

// create the length prefix
prefix := make([]byte, 4)
binary.BigEndian.PutUint32(prefix, uint32(len(message)))

// write the prefix and the data to the stream (checking errors)
_, err := conn.Write(prefix)
_, err = conn.Write(message)

并阅读消息

// read the length prefix
prefix := make([]byte, 4)
_, err = io.ReadFull(conn, prefix)


length := binary.BigEndian.Uint32(prefix)
// verify length if there are restrictions

message = make([]byte, int(length))
_, err = io.ReadFull(conn, message)

另见Golang:TCP 客户端/服务器数据分隔符

当然,您也可以使用现有的良好测试协议,如 HTTP、IRC 等来满足您的消息传递需求。go std 库带有一个简单的textproto,或者您可以选择将消息包含在统一编码中,例如 JSON。

于 2017-05-24T14:04:29.850 回答