Skip to content

Instantly share code, notes, and snippets.

@goyox86 goyox86/main.rs
Created Sep 25, 2017

Embed
What would you like to do?
Small Redox `mio` sample
extern crate mio;
use std::io::{Read, Write};
fn main() {
println!("TEST");
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 = "127.0.0.1:13265".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() {
SERVER => {
println!("SERVER");
// 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);
}
CLIENT => {
// The server just shuts down the socket, let's just exit
// from our event loop.
println!("CLIENT");
let mut string = String::new();
stream.read_to_string(&mut string).expect("client read");
println!("Client read: {}", string);
return;
}
token => {
panic!("UNKNOWN TOKEN {:?}", token);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.