Skip to content

Instantly share code, notes, and snippets.

@alexcrichton
Created January 27, 2017 00:27
Show Gist options
  • Save alexcrichton/7b97beda66d5e9b10321207cd69afbbc to your computer and use it in GitHub Desktop.
Save alexcrichton/7b97beda66d5e9b10321207cd69afbbc to your computer and use it in GitHub Desktop.
extern crate hyper;
extern crate futures;
extern crate pretty_env_logger;
extern crate num_cpus;
extern crate net2;
extern crate tokio_core;
use std::sync::Arc;
use std::thread;
use std::net::SocketAddr;
use futures::Stream;
use hyper::header::{ContentLength, ContentType};
use hyper::server::{Http, Service, Request, Response};
use net2::unix::UnixTcpBuilderExt;
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
static PHRASE: &'static [u8] = b"Hello World!";
#[derive(Clone, Copy)]
struct Hello;
impl Service for Hello {
type Request = Request;
type Response = Response;
type Error = hyper::Error;
type Future = ::futures::Finished<Response, hyper::Error>;
fn call(&self, _req: Request) -> Self::Future {
::futures::finished(
Response::new()
.with_header(ContentLength(PHRASE.len() as u64))
.with_header(ContentType::plaintext())
.with_body(PHRASE)
)
}
}
fn main() {
pretty_env_logger::init().unwrap();
let addr = "127.0.0.1:3000".parse().unwrap();
let protocol = Arc::new(Http::new());
for _ in 0..num_cpus::get() - 1 {
let protocol = protocol.clone();
thread::spawn(move || serve(&addr, &protocol));
}
serve(&addr, &protocol);
}
fn serve(addr: &SocketAddr, protocol: &Http) {
let mut core = Core::new().unwrap();
let handle = core.handle();
let listener = net2::TcpBuilder::new_v4().unwrap()
.reuse_port(true).unwrap()
.bind(addr).unwrap()
.listen(128).unwrap();
let listener = TcpListener::from_listener(listener, addr, &handle).unwrap();
core.run(listener.incoming().for_each(|(socket, addr)| {
protocol.bind_connection(&handle, socket, addr, Hello);
Ok(())
})).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment