• he/him

programming, video games, dadding. I happen to work for Xbox, but don't represent them.


more blog
dev.to/knutaf
discord
knutaf

i've been hacking away at my netcrab project for weeks now off and on, trying to add support for servicing multiple incoming network connections at once. the main problem is I started off writing it with the assumption that it would be a single socket being managed at a time. adding support for handling multiple sockets has made me change a lot of parts of the code.

I started off with a function simply called handle_tcp_stream that takes a tokio::net::TcpStream object and forwards all its data to be printed out to stdout, echoed back to the socket, etc.. likewise sends any data from elsewhere outbound to the socket too. it nicely encapsulated the logic of processing input from the network and producing output to send back to the network.

my first crack at adding support for multiple sockets was simply each time a new incoming socket is accepted, call handle_tcp_stream and shove the future into a vector. Then my futures::select handles accepting new sockets or servicing existing streams.

i got owned hard by the borrow checker at about this point. there's no way to mutably hold on to this vector of futures and keep resuming them. I had all kinds of errors like you wouldn't believe.

eventually I got lucky and stumbled upon the right tool for the job, which is FuturesUnordered. it lets me add new futures to the list without requiring a mutable borrow, which is just so nice. It lets any of the futures complete in any order and automatically removes them from the list when that happens. it's exactly what I needed.

funny how finding the right tool for the job makes things so much easier, huh?


You must log in to comment.