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. 36
      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
tmpBuf := make([]byte, BatchSizeInByte)
ILOOP:
for {
timeoutDuration := 10 * time.Second
s.SetReadDeadline(time.Now().Add(timeoutDuration)) s.SetReadDeadline(time.Now().Add(timeoutDuration))
if bytesToRead < BatchSizeInByte { m, err := io.ReadFull(r, tmpBuf)
// Read the last number of bytes less than 1024 if err != nil || m < contentLength {
tmpBuf = make([]byte, bytesToRead) log.Error("Read %v bytes, we need %v bytes", m, contentLength)
}
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 return []byte{}, err
} }
} contentBuf.Write(tmpBuf)
return contentBuf.Bytes(), nil return contentBuf.Bytes(), nil
} }

Loading…
Cancel
Save