Skip to content

Commit

Permalink
feat(server): add Server::from_tcp constructor
Browse files Browse the repository at this point in the history
Adds a constructor to build a `Server` from an `std::net::TcpListener`.

Closes #1602
  • Loading branch information
yoshuawuyts authored and seanmonstar committed Aug 8, 2018
1 parent 6e8417e commit bb4c5e2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,20 @@ pub mod conn;
#[cfg(feature = "runtime")] mod tcp;

use std::fmt;
#[cfg(feature = "runtime")] use std::net::SocketAddr;
#[cfg(feature = "runtime")] use std::net::{SocketAddr, TcpListener as StdTcpListener};

#[cfg(feature = "runtime")] use std::time::Duration;

use futures::{Future, Stream, Poll};
use tokio_io::{AsyncRead, AsyncWrite};
#[cfg(feature = "runtime")] use tokio_reactor;

use body::{Body, Payload};
use service::{NewService, Service};
// Renamed `Http` as `Http_` for now so that people upgrading don't see an
// error that `hyper::server::Http` is private...
use self::conn::{Http as Http_, SpawnAll};
#[cfg(feature = "runtime")] use self::tcp::{AddrIncoming};
#[cfg(feature = "runtime")] use self::tcp::AddrIncoming;

/// A listening HTTP server that accepts connections in both HTTP1 and HTTP2 by default.
///
Expand Down Expand Up @@ -117,6 +119,16 @@ impl Server<AddrIncoming, ()> {
AddrIncoming::new(addr, None)
.map(Server::builder)
}

/// Create a new instance from a `std::net::TcpListener` instance.
pub fn from_tcp(
listener: StdTcpListener,
) -> Result<Builder<AddrIncoming>, ::Error> {
let handle = tokio_reactor::Handle::current();
let incoming = AddrIncoming::from_tcp(listener, &handle)
.map_err(|err| ::Error::new_listen(err))?;
Ok(Self::builder(incoming))
}
}

#[cfg(feature = "runtime")]
Expand Down Expand Up @@ -275,4 +287,3 @@ impl Builder<AddrIncoming> {
self
}
}

14 changes: 14 additions & 0 deletions src/server/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ impl AddrIncoming {
})
}

pub(super) fn from_tcp(std_listener: StdTcpListener, handle: &Handle) -> ::Result<Self>{
let listener = TcpListener::from_std(std_listener, &handle)
.map_err(::Error::new_listen)?;
let addr = listener.local_addr().map_err(::Error::new_listen)?;
Ok(AddrIncoming {
listener,
addr: addr,
sleep_on_errors: true,
tcp_keepalive_timeout: None,
tcp_nodelay: false,
timeout: None,
})
}

/// Get the local address bound to this listener.
pub fn local_addr(&self) -> SocketAddr {
self.addr
Expand Down

0 comments on commit bb4c5e2

Please sign in to comment.