use safina::executor::Executor; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; #[test] fn main() { // Start a simple server that uses safina::net to listen on a port, // accept connections, and spawn tasks to send and receive data. safina::timer::start_timer_thread(); let executor: Arc = Arc::default(); let bind_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0); let listener = safina::net::TcpListener::bind(bind_addr).unwrap(); let listen_addr = listener.inner().local_addr().unwrap(); println!("SERVER listening on {}", &listen_addr); executor.spawn(async move { println!("SERVER loop starting"); loop { let (mut tcp_stream, remote_addr) = listener.accept().await.unwrap(); safina::executor::spawn(async move { println!("SERVER accepted connection {remote_addr}"); let mut request = String::new(); Box::pin(tcp_stream.read_to_string(&mut request)) .await .unwrap(); println!("SERVER received request {request:?}"); let response = "response1"; println!("SERVER sending response {response:?}"); tcp_stream.write_all(response.as_bytes()).await.unwrap(); }); } }); // Use std::net blocking sockets to connect to the server and send & receive data. println!("CLIENT connecting"); let mut tcp_stream = std::net::TcpStream::connect(listen_addr).unwrap(); let request = "request1"; println!("CLIENT sending request {request:?}"); std::io::Write::write_all(&mut tcp_stream, request.as_bytes()).unwrap(); tcp_stream.shutdown(std::net::Shutdown::Write).unwrap(); println!("CLIENT reading response"); let mut response = String::new(); std::io::Read::read_to_string(&mut tcp_stream, &mut response).unwrap(); println!("CLIENT received response {response:?}"); assert_eq!("response1", response); }