在 Go 中如何读取连接中的剩余字节?
时间:2024-03-14
浏览:260
作者:佚名
编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《在 Go 中如何读取连接中的剩余字节?》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。
问题内容
我正在尝试从 go 中的 tcp 连接读取数据。我有一个特定的标头格式,我首先尝试解析。因此,请读取前 12 个字节,其中包含与标头相关的信息。这告诉我剩余的消息长度是一定数量的字节。在本例中为 1607 字节。我尝试使用以下代码读取标头字节,然后尝试读取剩余字节。
import ("net"
log "github.com/sirupsen/logrus"
"bytes"
"encoding/binary"
)
func handleRequest(conn net.Conn) {
// Structs to make header parsing easiers
type encapSTHdrMsgType uint16
type encapSTHdrMsgEncap uint16
type encapSTHdr struct {
MsgType encapSTHdrMsgType
MsgEncap encapSTHdrMsgEncap
MsgHdrVersion uint16
Msgflag uint16
Msglen uint32
}
// Make a buffer to hold header data.
headerBuf := make([]byte, 12)
// Read the incoming header info into the buffer.
_, err := conn.Read(headerBuf)
if err != nil {
log.Debug("Error reading:", err.Error())
}
// Header is in big endian
var header encapSTHdr
headerReader := bytes.NewReader(headerBuf)
err = binary.Read(headerReader, binary.BigEndian, &header)
if err != nil {
log.Debugf("Could not read header bytes into the buffer: %v", err)
}
messageBuf := make([]byte, header.Msglen)
messageBufLen, err := conn.Read(messageBuf)
if err != nil {
log.Debugf("Error reading messages: %s", err.Error())
}
log.Debugf("The message buffer length is: %d", messageBufLen)
log.Debugf("The header message length is: %d", header.Msglen)
}
当我尝试通过创建所需长度 1607 的新缓冲区来读取剩余字节时,我得到一个包含数据的新字节数组,但它的长度仅为 1228。因此,我有两个问题:
1) 为什么 conn.read() 没有读取剩余字节?
2)现在我知道我可以使用 for 循环,直到读取所需的字节数并在完成后中断,但我想知道是否有更好的方法来做到这一点?
解决方案
Read 在数据可用时返回,而不是在数据填满缓冲区时返回。使用 io.ReadFull() 读取,直到缓冲区已满或从连接读取时出错。
_, err := io.ReadFull(conn, headerBuf) ... _, err := io.ReadFull(conn, messageBuf)
理论要掌握,实操不能落!以上关于《在 Go 中如何读取连接中的剩余字节?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
