simplify read message content code (#216)

pull/223/head
chaosma 6 years ago committed by GitHub
parent 0af1abfeb6
commit da32d1c0bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 40
      p2p/helper.go

@ -57,36 +57,16 @@ func ReadMessageContent(s Stream) ([]byte, error) {
log.Error("Failed reading the p2p message size field: only read", "Num of bytes", n) log.Error("Failed reading the p2p message size field: only read", "Num of bytes", n)
return contentBuf.Bytes(), err return contentBuf.Bytes(), err
} }
//log.Print(fourBytes)
// Number of bytes for the message content contentLength := int(binary.BigEndian.Uint32(fourBytes))
bytesToRead := binary.BigEndian.Uint32(fourBytes) tmpBuf := make([]byte, contentLength)
//log.Printf("The content size is %d bytes.", bytesToRead) timeoutDuration = 20 * time.Second
//// Read the content in chunk of 16 * 1024 bytes s.SetReadDeadline(time.Now().Add(timeoutDuration))
tmpBuf := make([]byte, BatchSizeInByte) m, err := io.ReadFull(r, tmpBuf)
ILOOP: if err != nil || m < contentLength {
for { log.Error("Read %v bytes, we need %v bytes", m, contentLength)
timeoutDuration := 10 * time.Second return []byte{}, err
s.SetReadDeadline(time.Now().Add(timeoutDuration))
if bytesToRead < BatchSizeInByte {
// Read the last number of bytes less than 1024
tmpBuf = make([]byte, bytesToRead)
}
n, err := r.Read(tmpBuf)
contentBuf.Write(tmpBuf[:n])
switch err {
case io.EOF:
// TODO: should we return error here, or just ignore it?
log.Error("EOF reached while reading p2p message")
break ILOOP
case nil:
bytesToRead -= uint32(n) // TODO: think about avoid the casting in every loop
if bytesToRead <= 0 {
break ILOOP
}
default:
log.Error("Error reading p2p message")
return []byte{}, err
}
} }
contentBuf.Write(tmpBuf)
return contentBuf.Bytes(), nil return contentBuf.Bytes(), nil
} }

Loading…
Cancel
Save