在Go中使用conn.Read()读取前几个字节后,如何继续读取剩余字节?
我正在尝试读取Go中的tcp连接。我有一个特定的头格式,我正试图首先解析。因此,读取头12个字节,其中包含与标头关联的信息。这告诉我剩余的消息长度是一定数量的字节。在本例中为1607字节。我在下面的代码中读取了头字节,然后尝试读取剩余的字节在Go中使用conn.Read()读取前几个字节后,如何继续读取剩余字节?,go,Go,我正在尝试读取Go中的tcp连接。我有一个特定的头格式,我正试图首先解析。因此,读取头12个字节,其中包含与标头关联的信息。这告诉我剩余的消息长度是一定数量的字节。在本例中为1607字节。我在下面的代码中读取了头字节,然后尝试读取剩余的字节 import ("net" log "github.com/sirupsen/logrus" "bytes" "encoding/binary" ) func handleRequest(conn net.Con
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循环,直到我读取了所需的字节数并在完成时中断,但我想知道是否有更好的方法来执行此操作?在数据可用时返回,而不是在数据填充缓冲区时返回。用于读取,直到缓冲区已满或从连接读取时出错
_, err := io.ReadFull(conn, headerBuf)
...
_, err := io.ReadFull(conn, messageBuf)