How to send Vec<u8> in tokio?


I’m trying to get a basic tcp server working in tokio…but i can’t seem to find a sample working for sending a buffer of Vec in the main loop? this compiles (so sorry for the warnings), I just need to send a byte buffer, how can i do it?

let buf = Bytes::new();
let snd = _writer.send(buf)
//this is where i’m confused to how to write code //

also where do i insert this code?


At what point would you like to send the buffer? As part of (or after) process_bytes()?


I’ll preempt your answer to the above with an assumption that you want to respond to each received buffer. This is one way to do it. It makes use of forward(), which (as the name implies) forwards all data from a Stream to a Sink. As long as the Stream keeps producing values (which in this case means as long as the remote doesn’t shutdown its write half of the socket) it’ll keep going.

In general, you don’t set up explicit loops when working with futures/tokio. Instead, you wire up the Stream and Sink portions so that the former feeds the latter.


so if i am to process the current buffer and create an outgoing buffer i could just

let mut outbuf = Bytes::new();
process_bytes(&inbuf, &outbuf);

so that process_bytes process incoming buf, then writes to outbuf which is sent by forward()?

Thank you very much


Yes, you can do that. Or create the outgoing buf inside process_bytes() and return it from there.