networking - 使用 bufio.NewReader(conn) 阅读整条消息

标签 networking encryption go chat public-key-exchange

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

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

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

最佳答案

发送二进制数据的一个简单选项是使用长度前缀。将数据大小编码为 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 client/server data delimiter

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

关于networking - 使用 bufio.NewReader(conn) 阅读整条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44159811/

相关文章:

c - 通信节点之间的 Nanomsg 消息加密

c# - 使用十六进制 key 的 TripleDESCryptoServiceProvider

json - 转换仅包含 1 个数组字段的 JSON

unit-testing - 如何在golang中测试主要的包功能?

c++ - Windows/Winsock UDP 数据包被分组在一起?

networking - 在Elasticsearch集群中 “IN THE SAME NETWORK”是什么意思?

encryption - 在 C# .NET Core 中,我应该如何使用在 HSM 中创建的签名对 CSR 进行签名?

python - 使用 Python 在 LAN 上查找事件节点

sockets - TCP端口复制器

dictionary - 戈朗 : Using a defined interface in a Map Value