Putting it all together in a connection handler
We have looked at a lot of different practices in isolation now. The true strength of these building blocks, however, comes from combining them. This recipe is going to show you how to combine some of them into a realistic starting point for the connection handling part of a server.
How to do it...
In the folder
bin
, create a file calledconnection_handler.rs
.Add the following code and run it with
cargo run --bin connection_handler
:
1 use std::sync::{Arc, RwLock}; 2 use std::net::Ipv6Addr; 3 use std::collections::HashMap; 4 use std::{thread, time}; 5 use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; 6 7 // Client holds whatever state your client might have 8 struct Client { 9 ip: Ipv6Addr, 10 } 11 12 // ConnectionHandler manages a list of connections 13 // in a parallelly safe way 14 struct ConnectionHandler { 15 // The clients are identified by a unique key 16 clients: RwLock<HashMap<usize, Client>>, 17 next_id...