How to send Vec<u8> in tokio?


#1

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 https://play.rust-lang.org/?gist=7b89e5052f6340d28277ffe3484d9efa&version=stable&mode=debug 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 //

tokio::spawn(snd)
also where do i insert this code?


#2

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


#3

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.


#4

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);
outbuf

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

Thank you very much


#5

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