Skip to content

Instantly share code, notes, and snippets.

Created Sep 25, 2017
What would you like to do?
Small Redox `mio` sample
extern crate mio;
use std::io::{Read, Write};
fn main() {
use mio::*;
use mio::net::{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);
let addr = "".parse().expect("addr");
// Setup the server socket
let server = TcpListener::bind(&addr).expect("TcpListener::bind");
println!("Bound to {}", addr);
// Create a poll instance
let poll = Poll::new().expect("Poll::new");
// Start listening for incoming connections
poll.register(&server, SERVER, Ready::readable(),
PollOpt::edge()).expect("poll.register server");
// Setup the client socket
let mut stream = TcpStream::connect(&addr).expect("connect");
// Register the socket
poll.register(&stream, CLIENT, Ready::readable(),
PollOpt::edge()).expect("poll.register client");
// Create storage for events
let mut events = Events::with_capacity(1024);
loop {
poll.poll(&mut events, None).expect("poll.poll");
for event in events.iter() {
match event.token() {
// Accept and drop the socket immediately, this will close
// the socket and notify the client of the EOF.
let (mut stream, addr) = server.accept().expect("server.accept");
println!("Accept from {}", addr);
let string = "Test";
stream.write(string.as_bytes()).expect("server write");
println!("Server write: {}", string);
// The server just shuts down the socket, let's just exit
// from our event loop.
let mut string = String::new();
stream.read_to_string(&mut string).expect("client read");
println!("Client read: {}", string);
token => {
panic!("UNKNOWN TOKEN {:?}", token);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment