Last active
March 23, 2019 02:37
-
-
Save voluntas/a9dac106a800ea0cebca817b65b2f164 to your computer and use it in GitHub Desktop.
はじめての Rust で UDP えこーさーばー
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 rotor; | |
use std::str; | |
use rotor::{EventSet, PollOpt, Loop, Config, Void}; | |
use rotor::mio::udp::UdpSocket; | |
use rotor::{Machine, Response, EarlyScope, Scope}; | |
struct Context; | |
enum Echo { | |
Server(UdpSocket), | |
} | |
impl Echo { | |
pub fn new(sock: UdpSocket, scope: &mut EarlyScope) -> Response<Echo, Void> { | |
scope.register(&sock, EventSet::readable(), PollOpt::edge()).unwrap(); | |
Response::ok(Echo::Server(sock)) | |
} | |
} | |
impl Machine for Echo { | |
type Context = Context; | |
type Seed = (); | |
fn create(_seed: (), _scope: &mut Scope<Context>) -> Response<Self, Void> { | |
unreachable!(); | |
} | |
fn ready(self, _events: EventSet, _scope: &mut Scope<Context>) -> Response<Self, ()> { | |
match self { | |
Echo::Server(sock) => { | |
let mut data = [0u8; 1024]; | |
match sock.recv_from(&mut data) { | |
Ok(Some((x, addr))) => { | |
match sock.send_to(&data[..x], &addr) { | |
Ok(_) => Response::ok(Echo::Server(sock)), | |
Err(_) => Response::done(), | |
} | |
} | |
Ok(None) => Response::done(), | |
Err(_) => Response::done(), | |
} | |
} | |
} | |
} | |
fn spawned(self, _scope: &mut Scope<Context>) -> Response<Self, ()> { | |
unreachable!(); | |
} | |
fn timeout(self, _scope: &mut Scope<Context>) -> Response<Self, ()> { | |
unreachable!(); | |
} | |
fn wakeup(self, _scope: &mut Scope<Context>) -> Response<Self, ()> { | |
unreachable!(); | |
} | |
} | |
fn main() { | |
let mut loop_creator = Loop::new(&Config::new()).unwrap(); | |
let addr = str::FromStr::from_str("127.0.0.1:5000").unwrap(); | |
let socket = UdpSocket::bound(&addr).unwrap(); | |
loop_creator.add_machine_with(|scope| Echo::new(socket, scope)) | |
.unwrap(); | |
loop_creator.run(Context).unwrap() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment