简体   繁体   English

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

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

I am working on a simple chat server and client in golang. 我正在使用golang中的简单聊天服务器和客户端。 I am having some trouble with reading messages from the net.Conn. 我在从net.conn读取消息时遇到了一些麻烦。 So far this is what I have been doing: 到目前为止,这是我一直在做的事情:

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

Since the user presses enter to send the message I only have to read until '\\n'. 由于用户按下Enter键发送消息,所以我只需要读到'\\ n'。 But I am now working on encryption and when sending the public keys between client and server the key sometimes contains '\\n', which makes it hard to get the whole key. 但是我现在正在进行加密,当在客户端和服务器之间发送公钥时,该密钥有时包含“ \\ n”,这使得很难获得整个密钥。 I am just wondering how I can read the whole message instead of stopping at a specific character. 我只是想知道如何阅读整个消息,而不是停在一个特定的字符上。 Thanks! 谢谢!

A simple option for sending binary data is to use a length prefix. 发送二进制数据的一个简单选项是使用长度前缀。 Encode the data size as a 32bit big endian integer, then read that amount of data. 将数据大小编码为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)

And to read the 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)

See also Golang: TCP client/server data delimiter 另请参阅Golang:TCP客户端/服务器数据定界符

You can also of course use an existing, well test protocol, like HTTP, IRC, etc. for your messaging needs. 当然,您也可以使用现有的,经过良好测试的协议(例如HTTP,IRC等)来满足您的消息传递需求。 The go std library comes with a simple textproto package , or you could opt to enclose the messages in a uniform encoding, like JSON. go std库带有一个简单的textproto软件包 ,或者您可以选择将消息封装为统一编码,例如JSON。

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

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