library

Online co-op book organization video game
git clone https://git.bradleygannon.com/library.git
Log | Files | Refs

net.rs (1078B)


      1 use std::{
      2     net::SocketAddr,
      3     sync::{
      4         Arc, Mutex,
      5         mpsc::{Receiver, Sender},
      6     },
      7     thread,
      8     time::Duration,
      9 };
     10 
     11 use common::{
     12     game::{Action, Response},
     13     net::{handle_network_read, handle_network_write},
     14 };
     15 use mio::{Interest, Poll, Token, net::TcpStream};
     16 
     17 const TOKEN: Token = Token(0);
     18 
     19 pub(crate) fn handle_connection(addr: SocketAddr, tx: Sender<Response>, rx: Receiver<Action>) {
     20     let mut stream = TcpStream::connect(addr).unwrap();
     21     let poll = Poll::new().unwrap();
     22     poll.registry()
     23         .register(&mut stream, TOKEN, Interest::READABLE)
     24         .unwrap();
     25     let shared_stream = Arc::new(Mutex::new(stream));
     26     let shared_stream_read = shared_stream.clone();
     27     let shared_stream_write = shared_stream.clone();
     28     let read_thread = thread::spawn(|| handle_network_read(poll, shared_stream_read, tx));
     29     let write_thread = thread::spawn(|| handle_network_write(shared_stream_write, rx));
     30     while !read_thread.is_finished() && !write_thread.is_finished() {
     31         thread::sleep(Duration::from_millis(500));
     32     }
     33 }