Skip to content

Instantly share code, notes, and snippets.

@tadman
Created June 23, 2015 17:05
Show Gist options
  • Select an option

  • Save tadman/6af2ae8b523d58af604c to your computer and use it in GitHub Desktop.

Select an option

Save tadman/6af2ae8b523d58af604c to your computer and use it in GitHub Desktop.

Revisions

  1. tadman created this gist Jun 23, 2015.
    80 changes: 80 additions & 0 deletions server.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,80 @@
    extern crate mio;

    use std::error::Error;

    use mio::*;
    use mio::tcp::{TcpListener, TcpStream};

    // Setup some tokens to allow us to identify which event is
    // for which socket.
    const SERVER: Token = Token(0);
    const CLIENT: Token = Token(1);

    // Define a handler to process the events
    struct MyHandler(TcpListener);

    impl Handler for MyHandler {
    type Timeout = ();
    type Message = ();

    fn readable(&mut self, event_loop: &mut EventLoop<MyHandler>, token: Token, _: ReadHint) {
    match token {
    SERVER => {
    let MyHandler(ref mut server) = *self;
    // Accept and drop the socket immediately, this will close
    // the socket and notify the client of the EOF.
    let _ = server.accept();

    print!("Client accepted");
    }
    CLIENT => {
    // The server just shuts down the socket, let's just
    // shutdown the event loop
    event_loop.shutdown();
    }
    _ => panic!("unexpected token"),
    }
    }
    }

    fn main() {
    let addr = "127.0.0.1:13265";

    print!("Server starting on {}\n", addr);

    // Setup the server socket
    let server = match TcpListener::bind(&addr) {
    Err(err) => panic!("Could not bind to {}: {}", addr, Error::description(&err)),
    Ok(v) => v
    };

    // Create an event loop
    let mut event_loop = match EventLoop::new() {
    Err(err) => panic!("Could not initialize event loop: {}", Error::description(&err)),
    Ok(v) => v
    };

    // Start listening for incoming connections
    match event_loop.register(&server, SERVER) {
    Err(err) => panic!("Failed to register server with event loop: {}", Error::description(&err)),
    Ok(v) => v
    };

    // Setup the client socket
    let sock = match TcpStream::connect(&addr) {
    Err(err) => panic!("Unable to connect to server: {}", Error::description(&err)),
    Ok(v) => v
    };

    // Register the socket
    match event_loop.register(&sock, CLIENT) {
    Err(err) => panic!("Failed to register client with event loop: {}", Error::description(&err)),
    Ok(v) => v
    };

    // Start handling events
    match event_loop.run(&mut MyHandler(server)) {
    Err(err) => panic!("Event loop failed to start: {}", Error::description(&err)),
    Ok(v) => v
    };
    }