Skip to content

Commit

Permalink
feat(net): add net2 crate and TcpBuilderConnector
Browse files Browse the repository at this point in the history
  • Loading branch information
Danyel Bayraktar committed Jul 25, 2015
1 parent 7e92633 commit cb210f6
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ authors = ["Sean McArthur <sean.monstar@gmail.com>",
keywords = ["http", "hyper", "hyperium"]

[dependencies]
net2 = "*"
httparse = "0.1"
language-tags = "0.0.7"
log = "0.3"
Expand Down
43 changes: 39 additions & 4 deletions src/net.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
//! A collection of traits abstracting over Listeners and Streams.
extern crate net2;
use std::any::{Any, TypeId};
use std::fmt;
use std::io::{self, ErrorKind, Read, Write};
use std::net::{SocketAddr, ToSocketAddrs, TcpStream, TcpListener, Shutdown};
use std::mem;

use self::net2::TcpBuilder;

#[cfg(feature = "openssl")]
pub use self::openssl::Openssl;

Expand Down Expand Up @@ -149,9 +152,12 @@ impl HttpListener {

/// Start listening to an address over HTTP.
pub fn new<To: ToSocketAddrs>(addr: To) -> ::Result<HttpListener> {
Ok(HttpListener(try!(TcpListener::bind(addr))))
HttpListener::from_builder(try!(try!(TcpBuilder::new_v4()).bind(addr)))
}

pub fn from_builder(builder: &TcpBuilder) -> ::Result<HttpListener> {
Ok(HttpListener(try!(builder.listen(128))))
}
}

impl NetworkListener for HttpListener {
Expand Down Expand Up @@ -241,11 +247,41 @@ impl NetworkConnector for HttpConnector {
type Stream = HttpStream;

fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> {
let addr = &(host, port);
TcpBuilderConnector::default().connect(host, port, scheme)
}
}

pub struct TcpBuilderConnector<T: ToSocketAddrs> {
pub ipv6: bool,
pub addr: Option<T>
}

impl Default for TcpBuilderConnector<SocketAddr> {
fn default() -> TcpBuilderConnector<SocketAddr> {
return TcpBuilderConnector{
ipv6: false,
addr: None
}
}
}

impl<T: ToSocketAddrs> NetworkConnector for TcpBuilderConnector<T> {
type Stream = HttpStream;

fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> {
let remote_addr = &(host, port);
Ok(try!(match scheme {
"http" => {
debug!("http scheme");
Ok(HttpStream(try!(TcpStream::connect(addr))))
let builder = try!(if self.ipv6 {
TcpBuilder::new_v6()
} else {
TcpBuilder::new_v4()
});
if let Some(ref local_addr) = self.addr {
try!(builder.bind(local_addr));
}
Ok(HttpStream(try!(builder.connect(remote_addr))))
},
_ => {
Err(io::Error::new(io::ErrorKind::InvalidInput,
Expand All @@ -255,7 +291,6 @@ impl NetworkConnector for HttpConnector {
}
}


/// An abstraction to allow any SSL implementation to be used with HttpsStreams.
pub trait Ssl {
/// The protected stream.
Expand Down

0 comments on commit cb210f6

Please sign in to comment.