Påd*_*dne 2 encryption networking chat go public-key-exchange
我正在golang中使用一个简单的聊天服务器和客户端.我在阅读net.Conn的消息时遇到了一些麻烦.到目前为止,这就是我一直在做的事情:
bufio.NewReader(conn).ReadString('\n')
Run Code Online (Sandbox Code Playgroud)
由于用户按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)
Run Code Online (Sandbox Code Playgroud)
并阅读消息
// 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)
Run Code Online (Sandbox Code Playgroud)
您当然也可以使用现有的测试协议,如HTTP,IRC等,以满足您的消息传递需求.go std库附带一个简单的textproto包,或者您可以选择将消息包含在统一编码中,如JSON.
| 归档时间: |
|
| 查看次数: |
1265 次 |
| 最近记录: |