Ignore next n bytes of TcpStream input

#1

Is there any easy and memory-efficient way to skip the next n bytes received on a BufReader<TcpStream>?

I am implementing a protocol in which messages have an optional payload with a length provided in the message header, and I want to be able to provide a reasonable error response when receiving a message that is too large for the service to handle. When such a message is received, the next message will come after the client has finished sending the entire too-large-to-handle payload, so somehow the protocol needs to ignore all the bytes in the payload (since they’re too large to read into memory). BufReader implements Seek when its underlying reader implements seek, but TcpStream does not.

0 Likes

#2

Here’s something that appears to work, using io::copy and io::Sink; in this line, r represents the buffered TCP reader:

std::io::copy(&mut r.take(len as u64), &mut std::io::sink());

Edit: take() actually consumes the BufReader by value, so this doesn’t actually work.

0 Likes

#3

You could do std::io::copy(&mut r.by_ref().take(len as u64), &mut std::io::sink());

3 Likes

#5

Strange, I thought I had tried that unsuccessfully already, but it does compile. Thank you!

0 Likes

#6

Note the by_ref, this will give you a mutable reference to the reader.

0 Likes

#7

Yes, that’s why I tried it before. I must have had some other error elsewhere in my code, though, and the declaration is take(self) -> ..., so I took by_ref back out.

0 Likes