How to read binary data from a socket and how to store them?

Hi all, I have been learning rust for several months, and I want to do some toy stuff with TCP.
I want to read binary data from a TcpSteam, and want to store it in a vector then serialize it in my own rules, and also I would like to write some binary data to a stream, is that possible in stable rust? thanks

You can write any &[u8] slice to a TcpStream using the write (or more conveniently, write_all) method from the Write trait. You can read into an &mut [u8] using the read (or more conveniently read_exact) from the Read trait.

You may want to read chapter 20 in the rust book, which you can find here. The data they happen to write is readable as ASCII, but writing binary is exactly the same — pass a byte array.

Hi alice, thanks for replying, I have read what you mentioned, but what I want is reading binary data not byte data from a socket, then store it in a vector like BitVec in collection, but it seems to be unstable, and I don't know how to read binary data from socket, should I read byte data from it then trans to binary?

The only kind of data that can be transferred via a TcpStream is a sequence of u8. This is not a limitation of Rust, but is how the internet works.

If you want to send some other kind of data, you must come up with a way to convert it into a sequence of bytes.

3 Likes

Usually the term "binary data" means a sequence of bytes, so a &[u8] (or Vec<u8>) in Rust. Do you have something different in mind?

If you're using the bitvec crate, that provides functions to construct a BitSlice or BitVec from a slice of bytes or owned Vec<u8>. But I'm not sure why you'd want to deserialize from one of those instead of from &[u8], which is much more common.

3 Likes

Sorry I didn't know that bit can't be read from socket, I thought bit was binary, thank you very much!

Technically that does also happen. A byte is nothing more or less than a sequence of 8 bits in modern hardware. You can even use bit shifting or bit masking to gain access to the individual bits in a given byte.