demo

    1. use mio::net::{TcpListener, TcpStream};
    2. use mio::{Events, Interest, Poll, Token};
    3. const SERVER: Token = Token(0);
    4. const CLINET: Token = Token(1);
    5. fn main() -> std::io::Result<()> {
    6. let mut poll = Poll::new()?;
    7. let mut events = Events::with_capacity(128);
    8. let addr = "127.0.0.1:8080".parse().unwrap();
    9. let mut server = TcpListener::bind(addr)?;
    10. poll.registry()
    11. .register(&mut server, SERVER, Interest::READABLE)?;
    12. let mut client = TcpStream::connect(addr)?;
    13. poll.registry()
    14. .register(&mut client, CLINET, Interest::READABLE | Interest::WRITABLE)?;
    15. // std::thread::sleep(std::time::Duration::from_secs(3));
    16. loop {
    17. poll.poll(&mut events, None)?;
    18. for event in events.iter() {
    19. match event.token() {
    20. SERVER => {
    21. let connection = server.accept();
    22. println!("server recv a connection");
    23. drop(connection);
    24. }
    25. CLINET => {
    26. if event.is_writable() {
    27. println!("client write");
    28. }
    29. if event.is_readable() {
    30. println!("client read");
    31. }
    32. // return Ok(());
    33. }
    34. _ => unreachable!(),
    35. }
    36. }
    37. }
    38. }