繁体   English   中英

使用bufio.NewReader(conn)阅读整个消息

[英]Read whole message with bufio.NewReader(conn)

我正在使用golang中的简单聊天服务器和客户端。 我在从net.conn读取消息时遇到了一些麻烦。 到目前为止,这是我一直在做的事情:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM