Why would you read 1024 bytes? Read 5 bytes, repeating the read if necessary until you've actually got 5 bytes (or an error). Then you know how long the message itself is: so repeatedly read until you've got all the data for the message. (On each call you only ask for as much data as you actually want, of course - so if when you're reading the header you first read 2 bytes, then on the next call you request 3 bytes, i.e. the remainder of the header.)
Reading more than you know you need is just asking for complexity - it means you've got to remember that data somewhere for the next read.