-
-
Save doitian/d52ff7ce6185dedd444cc172a4c25758 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate mio; // 0.6.14 | |
use mio::event::Evented; | |
use mio::{Poll, PollOpt, Ready, Registration, Token, Events}; | |
use std::io; | |
use std::thread; | |
use std::time::{Instant, Duration}; | |
pub struct Deadline { | |
when: Instant, | |
registration: Registration, | |
} | |
impl Deadline { | |
pub fn new(when: Instant) -> Deadline { | |
let (registration, set_readiness) = Registration::new2(); | |
thread::spawn(move || { | |
let now = Instant::now(); | |
if now < when { | |
thread::sleep(when - now); | |
} | |
let _ = set_readiness.set_readiness(Ready::readable()); | |
}); | |
Deadline { | |
when: when, | |
registration: registration, | |
} | |
} | |
pub fn is_elapsed(&self) -> bool { | |
Instant::now() >= self.when | |
} | |
} | |
impl Evented for Deadline { | |
fn register( | |
&self, | |
poll: &Poll, | |
token: Token, | |
interest: Ready, | |
opts: PollOpt, | |
) -> io::Result<()> { | |
Evented::register(&self.registration, poll, token, interest, opts) | |
} | |
fn reregister( | |
&self, | |
poll: &Poll, | |
token: Token, | |
interest: Ready, | |
opts: PollOpt, | |
) -> io::Result<()> { | |
Evented::reregister(&self.registration, poll, token, interest, opts) | |
} | |
fn deregister(&self, poll: &Poll) -> io::Result<()> { | |
Evented::deregister(&self.registration, poll) | |
} | |
} | |
fn main() { | |
let deadline = Deadline::new(Instant::now() + Duration::new(2, 0)); | |
// Create a poll instance | |
let poll = Poll::new().unwrap(); | |
poll.register(&deadline, Token(0), Ready::readable(), PollOpt::edge()) | |
.unwrap(); | |
// Create storage for events | |
let mut events = Events::with_capacity(1024); | |
poll.poll(&mut events, None).unwrap(); | |
for event in events.iter() { | |
match event.token() { | |
Token(0) => { | |
println!("Deadline is due? {:?}", deadline.is_elapsed()); | |
// Accept and drop the socket immediately, this will close | |
// the socket and notify the client of the EOF. | |
} | |
_ => unreachable!(), | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment