Created
September 25, 2017 12:24
-
-
Save anonymous/fc693d83d288462df250816fe4b769e4 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
This file contains 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
//[dependencies] | |
//time = "0.1" | |
//futures = "0.1.14" | |
//tokio-core = "0.1" | |
//tokio-periodic = "0.1" | |
#[macro_use] | |
extern crate tokio_core; | |
extern crate time; | |
extern crate futures; | |
extern crate tokio_periodic; | |
use std::net::{SocketAddr}; | |
use futures::Stream; | |
use futures::Future; | |
use futures::Poll; | |
use tokio_core::net::UdpSocket; | |
struct Server { | |
socket: UdpSocket, | |
buf: Vec<u8>, | |
to_send: Option<(usize, SocketAddr)>, | |
} | |
impl Future for Server { | |
type Item = (); | |
type Error = std::io::Error; | |
fn poll(&mut self) -> Poll<(), std::io::Error> { | |
loop { | |
if let Some((size, peer)) = self.to_send { | |
let amt = try_nb!(self.socket.send_to(&self.buf[..size], &peer)); | |
println!("[{}]: Echoed {}/{} bytes to {}", time::SteadyTime::now(), amt, size, peer); | |
self.to_send = None; | |
} | |
self.to_send = Some(try_nb!(self.socket.recv_from(&mut self.buf))); | |
let cnt = match self.to_send { | |
Some((cnt, _)) => cnt, | |
_ => 0 | |
}; | |
println!("[{}]: readed: {:?}", time::SteadyTime::now(), &self.buf[..cnt]); | |
} | |
} | |
} | |
struct TimerWorker { | |
} | |
impl Future for TimerWorker { | |
type Item = (); | |
type Error = std::io::Error; | |
fn poll(&mut self) -> Poll<(), std::io::Error> { | |
println!("[{}]: Periodic timer work", time::SteadyTime::now()); | |
Ok(futures::Async::Ready(())) | |
} | |
} | |
fn main() { | |
let mut core = tokio_core::reactor::Core::new().unwrap(); | |
let handle = core.handle(); | |
let timer = tokio_periodic::PeriodicTimer::new(&handle).unwrap(); | |
timer.reset(::std::time::Duration::new(0, 100_000_000)).unwrap(); | |
let cbt = | |
timer.for_each(|x| { TimerWorker{} }); | |
let addr = "255.255.255.255:11224".parse::<SocketAddr>().unwrap(); | |
let udp_sock = UdpSocket::bind(&addr, &handle) | |
.expect("Couldn't bind udp socket"); | |
let timer_and_udp_listener = cbt.join(Server{socket: udp_sock, buf: vec![0; 64], to_send: None}); | |
core.run(timer_and_udp_listener); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment