rust/src/libstd/io/net/tcp.rs

837 lines
25 KiB
Rust
Raw Normal View History

// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
//! TCP network connections
//!
//! This module contains the ability to open a TCP stream to a socket address,
//! as well as creating a socket server to accept incoming connections. The
//! destination and binding addresses can either be an IPv4 or IPv6 address.
//!
//! A TCP connection implements the `Reader` and `Writer` traits, while the TCP
//! listener (socket server) implements the `Listener` and `Acceptor` traits.
use clone::Clone;
use io::IoResult;
2013-11-10 22:46:32 -08:00
use io::net::ip::SocketAddr;
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
use io::{Reader, Writer, Listener, Acceptor};
use kinds::Send;
use option::{None, Some, Option};
use rt::rtio::{IoFactory, LocalIo, RtioSocket, RtioTcpListener};
use rt::rtio::{RtioTcpAcceptor, RtioTcpStream};
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// A structure which represents a TCP stream between a local socket and a
/// remote socket.
///
/// # Example
///
/// ```rust
/// # #![allow(unused_must_use)]
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// use std::io::net::tcp::TcpStream;
/// use std::io::net::ip::{Ipv4Addr, SocketAddr};
///
/// let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 34254 };
/// let mut stream = TcpStream::connect(addr);
///
/// stream.write([1]);
/// let mut buf = [0];
/// stream.read(buf);
/// drop(stream); // close the connection
/// ```
pub struct TcpStream {
2014-03-27 15:09:47 -07:00
obj: ~RtioTcpStream:Send
}
impl TcpStream {
fn new(s: ~RtioTcpStream:Send) -> TcpStream {
TcpStream { obj: s }
}
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// Creates a TCP connection to a remote socket address.
///
/// If no error is encountered, then `Ok(stream)` is returned.
pub fn connect(addr: SocketAddr) -> IoResult<TcpStream> {
LocalIo::maybe_raise(|io| {
io.tcp_connect(addr, None).map(TcpStream::new)
})
}
/// Creates a TCP connection to a remote socket address, timing out after
/// the specified number of milliseconds.
///
/// This is the same as the `connect` method, except that if the timeout
/// specified (in milliseconds) elapses before a connection is made an error
/// will be returned. The error's kind will be `TimedOut`.
#[experimental = "the timeout argument may eventually change types"]
pub fn connect_timeout(addr: SocketAddr,
timeout_ms: u64) -> IoResult<TcpStream> {
LocalIo::maybe_raise(|io| {
io.tcp_connect(addr, Some(timeout_ms)).map(TcpStream::new)
})
}
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// Returns the socket address of the remote peer of this TCP connection.
pub fn peer_name(&mut self) -> IoResult<SocketAddr> {
self.obj.peer_name()
}
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// Returns the socket address of the local half of this TCP connection.
pub fn socket_name(&mut self) -> IoResult<SocketAddr> {
self.obj.socket_name()
}
}
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
impl Clone for TcpStream {
/// Creates a new handle to this TCP stream, allowing for simultaneous reads
/// and writes of this connection.
///
/// The underlying TCP stream will not be closed until all handles to the
/// stream have been deallocated. All handles will also follow the same
/// stream, but two concurrent reads will not receive the same data.
/// Instead, the first read will receive the first packet received, and the
/// second read will receive the second packet.
fn clone(&self) -> TcpStream {
TcpStream { obj: self.obj.clone() }
}
}
impl Reader for TcpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.obj.read(buf) }
}
impl Writer for TcpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.obj.write(buf) }
}
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// A structure representing a socket server. This listener is used to create a
/// `TcpAcceptor` which can be used to accept sockets on a local port.
///
/// # Example
///
/// ```rust
/// # fn main() { }
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// # fn foo() {
/// # #![allow(dead_code)]
/// use std::io::{TcpListener, TcpStream};
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// use std::io::net::ip::{Ipv4Addr, SocketAddr};
/// use std::io::{Acceptor, Listener};
///
/// let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 80 };
/// let listener = TcpListener::bind(addr);
///
/// // bind the listener to the specified address
/// let mut acceptor = listener.listen();
///
/// fn handle_client(mut stream: TcpStream) {
/// // ...
/// # &mut stream; // silence unused mutability/variable warning
/// }
/// // accept connections and process them, spawning a new tasks for each one
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// for stream in acceptor.incoming() {
/// match stream {
/// Err(e) => { /* connection failed */ }
/// Ok(stream) => spawn(proc() {
/// // connection succeeded
/// handle_client(stream)
/// })
/// }
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// }
///
/// // close the socket server
/// drop(acceptor);
/// # }
/// ```
pub struct TcpListener {
2014-03-27 15:09:47 -07:00
obj: ~RtioTcpListener:Send
}
impl TcpListener {
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// Creates a new `TcpListener` which will be bound to the specified local
/// socket address. This listener is not ready for accepting connections,
/// `listen` must be called on it before that's possible.
///
/// Binding with a port number of 0 will request that the OS assigns a port
/// to this listener. The port allocated can be queried via the
/// `socket_name` function.
pub fn bind(addr: SocketAddr) -> IoResult<TcpListener> {
LocalIo::maybe_raise(|io| {
io.tcp_bind(addr).map(|l| TcpListener { obj: l })
})
}
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// Returns the local socket address of this listener.
pub fn socket_name(&mut self) -> IoResult<SocketAddr> {
self.obj.socket_name()
}
}
impl Listener<TcpStream, TcpAcceptor> for TcpListener {
fn listen(self) -> IoResult<TcpAcceptor> {
self.obj.listen().map(|acceptor| TcpAcceptor { obj: acceptor })
}
}
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
/// The accepting half of a TCP socket server. This structure is created through
/// a `TcpListener`'s `listen` method, and this object can be used to accept new
/// `TcpStream` instances.
pub struct TcpAcceptor {
2014-03-27 15:09:47 -07:00
obj: ~RtioTcpAcceptor:Send
}
impl TcpAcceptor {
/// Prevents blocking on all future accepts after `ms` milliseconds have
/// elapsed.
///
/// This function is used to set a deadline after which this acceptor will
/// time out accepting any connections. The argument is the relative
/// distance, in milliseconds, to a point in the future after which all
/// accepts will fail.
///
/// If the argument specified is `None`, then any previously registered
/// timeout is cleared.
///
/// A timeout of `0` can be used to "poll" this acceptor to see if it has
/// any pending connections. All pending connections will be accepted,
/// regardless of whether the timeout has expired or not (the accept will
/// not block in this case).
///
/// # Example
///
/// ```no_run
/// # #![allow(experimental)]
/// use std::io::net::tcp::TcpListener;
/// use std::io::net::ip::{SocketAddr, Ipv4Addr};
/// use std::io::{Listener, Acceptor, TimedOut};
///
/// let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 8482 };
/// let mut a = TcpListener::bind(addr).listen().unwrap();
///
/// // After 100ms have passed, all accepts will fail
/// a.set_timeout(Some(100));
///
/// match a.accept() {
/// Ok(..) => println!("accepted a socket"),
/// Err(ref e) if e.kind == TimedOut => { println!("timed out!"); }
/// Err(e) => println!("err: {}", e),
/// }
///
/// // Reset the timeout and try again
/// a.set_timeout(Some(100));
/// let socket = a.accept();
///
/// // Clear the timeout and block indefinitely waiting for a connection
/// a.set_timeout(None);
/// let socket = a.accept();
/// ```
#[experimental = "the type of the argument and name of this function are \
subject to change"]
pub fn set_timeout(&mut self, ms: Option<u64>) { self.obj.set_timeout(ms); }
}
impl Acceptor<TcpStream> for TcpAcceptor {
fn accept(&mut self) -> IoResult<TcpStream> {
self.obj.accept().map(TcpStream::new)
}
}
#[cfg(test)]
#[allow(experimental)]
mod test {
use super::*;
use io::net::ip::SocketAddr;
2013-11-10 22:46:32 -08:00
use io::*;
use prelude::*;
// FIXME #11530 this fails on android because tests are run as root
2013-12-27 17:50:16 -08:00
iotest!(fn bind_error() {
2014-01-30 14:10:53 -08:00
let addr = SocketAddr { ip: Ipv4Addr(0, 0, 0, 0), port: 1 };
match TcpListener::bind(addr) {
Ok(..) => fail!(),
Err(e) => assert_eq!(e.kind, PermissionDenied),
}
} #[ignore(cfg(windows))] #[ignore(cfg(target_os = "android"))])
2013-12-27 17:50:16 -08:00
iotest!(fn connect_error() {
2014-01-30 14:10:53 -08:00
let addr = SocketAddr { ip: Ipv4Addr(0, 0, 0, 0), port: 1 };
match TcpStream::connect(addr) {
Ok(..) => fail!(),
Err(e) => assert_eq!(e.kind, ConnectionRefused),
}
2013-12-27 17:50:16 -08:00
})
2013-12-27 17:50:16 -08:00
iotest!(fn smoke_test_ip4() {
let addr = next_test_ip4();
let mut acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
2013-12-05 18:19:06 -08:00
let mut stream = TcpStream::connect(addr);
2014-01-30 14:10:53 -08:00
stream.write([99]).unwrap();
});
let mut stream = acceptor.accept();
let mut buf = [0];
2014-01-30 14:10:53 -08:00
stream.read(buf).unwrap();
assert!(buf[0] == 99);
2013-12-27 17:50:16 -08:00
})
2013-12-27 17:50:16 -08:00
iotest!(fn smoke_test_ip6() {
let addr = next_test_ip6();
let mut acceptor = TcpListener::bind(addr).listen();
2013-07-02 16:40:57 -07:00
spawn(proc() {
2013-12-05 18:19:06 -08:00
let mut stream = TcpStream::connect(addr);
2014-01-30 14:10:53 -08:00
stream.write([99]).unwrap();
});
let mut stream = acceptor.accept();
let mut buf = [0];
2014-01-30 14:10:53 -08:00
stream.read(buf).unwrap();
assert!(buf[0] == 99);
2013-12-27 17:50:16 -08:00
})
2013-07-02 16:40:57 -07:00
2013-12-27 17:50:16 -08:00
iotest!(fn read_eof_ip4() {
let addr = next_test_ip4();
let mut acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
2013-12-05 18:19:06 -08:00
let _stream = TcpStream::connect(addr);
// Close
});
let mut stream = acceptor.accept();
let mut buf = [0];
let nread = stream.read(buf);
2014-01-30 14:10:53 -08:00
assert!(nread.is_err());
2013-12-27 17:50:16 -08:00
})
2013-12-27 17:50:16 -08:00
iotest!(fn read_eof_ip6() {
let addr = next_test_ip6();
let mut acceptor = TcpListener::bind(addr).listen();
2013-07-02 16:40:57 -07:00
spawn(proc() {
2013-12-05 18:19:06 -08:00
let _stream = TcpStream::connect(addr);
// Close
});
let mut stream = acceptor.accept();
let mut buf = [0];
let nread = stream.read(buf);
2014-01-30 14:10:53 -08:00
assert!(nread.is_err());
2013-12-27 17:50:16 -08:00
})
2013-07-02 16:40:57 -07:00
2013-12-27 17:50:16 -08:00
iotest!(fn read_eof_twice_ip4() {
let addr = next_test_ip4();
let mut acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
2013-12-05 18:19:06 -08:00
let _stream = TcpStream::connect(addr);
// Close
});
let mut stream = acceptor.accept();
let mut buf = [0];
let nread = stream.read(buf);
2014-01-30 14:10:53 -08:00
assert!(nread.is_err());
match stream.read(buf) {
Ok(..) => fail!(),
Err(ref e) => {
assert!(e.kind == NotConnected || e.kind == EndOfFile,
"unknown kind: {:?}", e.kind);
}
2014-01-30 14:10:53 -08:00
}
2013-12-27 17:50:16 -08:00
})
2013-12-27 17:50:16 -08:00
iotest!(fn read_eof_twice_ip6() {
let addr = next_test_ip6();
let mut acceptor = TcpListener::bind(addr).listen();
2013-07-02 16:40:57 -07:00
spawn(proc() {
2013-12-05 18:19:06 -08:00
let _stream = TcpStream::connect(addr);
// Close
});
let mut stream = acceptor.accept();
let mut buf = [0];
let nread = stream.read(buf);
2014-01-30 14:10:53 -08:00
assert!(nread.is_err());
match stream.read(buf) {
Ok(..) => fail!(),
Err(ref e) => {
assert!(e.kind == NotConnected || e.kind == EndOfFile,
"unknown kind: {:?}", e.kind);
}
2014-01-30 14:10:53 -08:00
}
2013-12-27 17:50:16 -08:00
})
2013-07-02 16:40:57 -07:00
2013-12-27 17:50:16 -08:00
iotest!(fn write_close_ip4() {
let addr = next_test_ip4();
let mut acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
2013-12-05 18:19:06 -08:00
let _stream = TcpStream::connect(addr);
// Close
});
let mut stream = acceptor.accept();
let buf = [0];
loop {
2014-01-30 14:10:53 -08:00
match stream.write(buf) {
Ok(..) => {}
Err(e) => {
assert!(e.kind == ConnectionReset ||
e.kind == BrokenPipe ||
e.kind == ConnectionAborted,
"unknown error: {:?}", e);
break;
}
}
}
2013-12-27 17:50:16 -08:00
})
2013-12-27 17:50:16 -08:00
iotest!(fn write_close_ip6() {
let addr = next_test_ip6();
let mut acceptor = TcpListener::bind(addr).listen();
2013-07-02 16:40:57 -07:00
spawn(proc() {
2013-12-05 18:19:06 -08:00
let _stream = TcpStream::connect(addr);
// Close
});
let mut stream = acceptor.accept();
let buf = [0];
loop {
2014-01-30 14:10:53 -08:00
match stream.write(buf) {
Ok(..) => {}
Err(e) => {
assert!(e.kind == ConnectionReset ||
e.kind == BrokenPipe ||
e.kind == ConnectionAborted,
"unknown error: {:?}", e);
break;
}
}
}
2013-12-27 17:50:16 -08:00
})
2013-07-02 16:40:57 -07:00
2013-12-27 17:50:16 -08:00
iotest!(fn multiple_connect_serial_ip4() {
let addr = next_test_ip4();
let max = 10u;
let mut acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
for _ in range(0, max) {
2013-12-05 18:19:06 -08:00
let mut stream = TcpStream::connect(addr);
2014-01-30 14:10:53 -08:00
stream.write([99]).unwrap();
}
});
for ref mut stream in acceptor.incoming().take(max) {
let mut buf = [0];
2014-01-30 14:10:53 -08:00
stream.read(buf).unwrap();
assert_eq!(buf[0], 99);
}
2013-12-27 17:50:16 -08:00
})
2013-12-27 17:50:16 -08:00
iotest!(fn multiple_connect_serial_ip6() {
let addr = next_test_ip6();
let max = 10u;
let mut acceptor = TcpListener::bind(addr).listen();
2013-07-02 16:40:57 -07:00
spawn(proc() {
for _ in range(0, max) {
2013-12-05 18:19:06 -08:00
let mut stream = TcpStream::connect(addr);
2014-01-30 14:10:53 -08:00
stream.write([99]).unwrap();
}
});
for ref mut stream in acceptor.incoming().take(max) {
let mut buf = [0];
2014-01-30 14:10:53 -08:00
stream.read(buf).unwrap();
assert_eq!(buf[0], 99);
}
2013-12-27 17:50:16 -08:00
})
2013-07-02 16:40:57 -07:00
2013-12-27 17:50:16 -08:00
iotest!(fn multiple_connect_interleaved_greedy_schedule_ip4() {
let addr = next_test_ip4();
static MAX: int = 10;
let acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
let mut acceptor = acceptor;
for (i, stream) in acceptor.incoming().enumerate().take(MAX as uint) {
// Start another task to handle the connection
spawn(proc() {
let mut stream = stream;
let mut buf = [0];
2014-01-30 14:10:53 -08:00
stream.read(buf).unwrap();
assert!(buf[0] == i as u8);
debug!("read");
});
2013-05-06 14:28:16 -07:00
}
});
2013-05-06 14:28:16 -07:00
connect(0, addr);
fn connect(i: int, addr: SocketAddr) {
if i == MAX { return }
spawn(proc() {
debug!("connecting");
let mut stream = TcpStream::connect(addr);
// Connect again before writing
connect(i + 1, addr);
debug!("writing");
2014-01-30 14:10:53 -08:00
stream.write([i as u8]).unwrap();
});
2013-05-06 14:28:16 -07:00
}
2013-12-27 17:50:16 -08:00
})
2013-05-06 14:28:16 -07:00
2013-12-27 17:50:16 -08:00
iotest!(fn multiple_connect_interleaved_greedy_schedule_ip6() {
let addr = next_test_ip6();
static MAX: int = 10;
let acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
let mut acceptor = acceptor;
for (i, stream) in acceptor.incoming().enumerate().take(MAX as uint) {
// Start another task to handle the connection
spawn(proc() {
let mut stream = stream;
let mut buf = [0];
2014-01-30 14:10:53 -08:00
stream.read(buf).unwrap();
assert!(buf[0] == i as u8);
debug!("read");
});
2013-07-02 16:40:57 -07:00
}
});
2013-07-02 16:40:57 -07:00
connect(0, addr);
fn connect(i: int, addr: SocketAddr) {
if i == MAX { return }
spawn(proc() {
debug!("connecting");
let mut stream = TcpStream::connect(addr);
// Connect again before writing
connect(i + 1, addr);
debug!("writing");
2014-01-30 14:10:53 -08:00
stream.write([i as u8]).unwrap();
});
2013-07-02 16:40:57 -07:00
}
2013-12-27 17:50:16 -08:00
})
2013-07-02 16:40:57 -07:00
2013-12-27 17:50:16 -08:00
iotest!(fn multiple_connect_interleaved_lazy_schedule_ip4() {
static MAX: int = 10;
let addr = next_test_ip4();
let acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
let mut acceptor = acceptor;
for stream in acceptor.incoming().take(MAX as uint) {
// Start another task to handle the connection
spawn(proc() {
let mut stream = stream;
let mut buf = [0];
2014-01-30 14:10:53 -08:00
stream.read(buf).unwrap();
assert!(buf[0] == 99);
debug!("read");
});
2013-07-02 16:40:57 -07:00
}
});
2013-07-02 16:40:57 -07:00
connect(0, addr);
fn connect(i: int, addr: SocketAddr) {
if i == MAX { return }
spawn(proc() {
debug!("connecting");
let mut stream = TcpStream::connect(addr);
// Connect again before writing
connect(i + 1, addr);
debug!("writing");
2014-01-30 14:10:53 -08:00
stream.write([99]).unwrap();
});
2013-07-02 16:40:57 -07:00
}
2013-12-27 17:50:16 -08:00
})
iotest!(fn multiple_connect_interleaved_lazy_schedule_ip6() {
static MAX: int = 10;
let addr = next_test_ip6();
let acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
let mut acceptor = acceptor;
for stream in acceptor.incoming().take(MAX as uint) {
// Start another task to handle the connection
spawn(proc() {
let mut stream = stream;
let mut buf = [0];
2014-01-30 14:10:53 -08:00
stream.read(buf).unwrap();
assert!(buf[0] == 99);
debug!("read");
});
2013-05-06 14:28:16 -07:00
}
});
2013-05-06 14:28:16 -07:00
connect(0, addr);
fn connect(i: int, addr: SocketAddr) {
if i == MAX { return }
spawn(proc() {
debug!("connecting");
let mut stream = TcpStream::connect(addr);
// Connect again before writing
connect(i + 1, addr);
debug!("writing");
2014-01-30 14:10:53 -08:00
stream.write([99]).unwrap();
});
2013-05-06 14:28:16 -07:00
}
2013-12-27 17:50:16 -08:00
})
2013-05-06 14:28:16 -07:00
2013-12-27 17:50:16 -08:00
pub fn socket_name(addr: SocketAddr) {
let mut listener = TcpListener::bind(addr).unwrap();
2013-07-26 05:02:53 -04:00
// Make sure socket_name gives
// us the socket we binded to.
let so_name = listener.socket_name();
2014-01-30 14:10:53 -08:00
assert!(so_name.is_ok());
assert_eq!(addr, so_name.unwrap());
2013-07-26 05:02:53 -04:00
}
2013-12-27 17:50:16 -08:00
pub fn peer_name(addr: SocketAddr) {
let acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
let mut acceptor = acceptor;
2014-01-30 14:10:53 -08:00
acceptor.accept().unwrap();
});
2013-07-26 05:02:53 -04:00
let stream = TcpStream::connect(addr);
2013-07-26 05:02:53 -04:00
2014-01-30 14:10:53 -08:00
assert!(stream.is_ok());
let mut stream = stream.unwrap();
2013-07-26 05:02:53 -04:00
// Make sure peer_name gives us the
// address/port of the peer we've
// connected to.
let peer_name = stream.peer_name();
2014-01-30 14:10:53 -08:00
assert!(peer_name.is_ok());
assert_eq!(addr, peer_name.unwrap());
2013-07-26 05:02:53 -04:00
}
2013-12-27 17:50:16 -08:00
iotest!(fn socket_and_peer_name_ip4() {
2013-07-26 05:02:53 -04:00
peer_name(next_test_ip4());
socket_name(next_test_ip4());
2013-12-27 17:50:16 -08:00
})
2013-07-26 05:02:53 -04:00
2013-12-27 17:50:16 -08:00
iotest!(fn socket_and_peer_name_ip6() {
// FIXME: peer name is not consistent
2013-07-26 05:02:53 -04:00
//peer_name(next_test_ip6());
socket_name(next_test_ip6());
2013-12-27 17:50:16 -08:00
})
iotest!(fn partial_read() {
let addr = next_test_ip4();
let (tx, rx) = channel();
spawn(proc() {
2014-01-30 14:10:53 -08:00
let mut srv = TcpListener::bind(addr).listen().unwrap();
tx.send(());
let mut cl = srv.accept().unwrap();
2014-01-30 14:10:53 -08:00
cl.write([10]).unwrap();
let mut b = [0];
2014-01-30 14:10:53 -08:00
cl.read(b).unwrap();
tx.send(());
});
rx.recv();
let mut c = TcpStream::connect(addr).unwrap();
let mut b = [0, ..10];
2014-01-30 14:10:53 -08:00
assert_eq!(c.read(b), Ok(1));
c.write([1]).unwrap();
rx.recv();
})
iotest!(fn double_bind() {
2014-01-30 14:10:53 -08:00
let addr = next_test_ip4();
let listener = TcpListener::bind(addr).unwrap().listen();
assert!(listener.is_ok());
match TcpListener::bind(addr).listen() {
Ok(..) => fail!(),
Err(e) => {
assert!(e.kind == ConnectionRefused || e.kind == OtherIoError);
}
}
})
iotest!(fn fast_rebind() {
let addr = next_test_ip4();
let (tx, rx) = channel();
spawn(proc() {
rx.recv();
2014-01-30 14:10:53 -08:00
let _stream = TcpStream::connect(addr).unwrap();
// Close
rx.recv();
});
{
let mut acceptor = TcpListener::bind(addr).listen();
tx.send(());
{
2014-01-30 14:10:53 -08:00
let _stream = acceptor.accept().unwrap();
// Close client
tx.send(());
}
// Close listener
}
let _listener = TcpListener::bind(addr);
})
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
iotest!(fn tcp_clone_smoke() {
let addr = next_test_ip4();
let mut acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
let mut s = TcpStream::connect(addr);
let mut buf = [0, 0];
assert_eq!(s.read(buf), Ok(1));
assert_eq!(buf[0], 1);
s.write([2]).unwrap();
});
let mut s1 = acceptor.accept().unwrap();
let s2 = s1.clone();
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
spawn(proc() {
let mut s2 = s2;
rx1.recv();
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
s2.write([1]).unwrap();
tx2.send(());
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
});
tx1.send(());
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
let mut buf = [0, 0];
assert_eq!(s1.read(buf), Ok(1));
rx2.recv();
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
})
iotest!(fn tcp_clone_two_read() {
let addr = next_test_ip6();
let mut acceptor = TcpListener::bind(addr).listen();
let (tx1, rx) = channel();
let tx2 = tx1.clone();
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
spawn(proc() {
let mut s = TcpStream::connect(addr);
s.write([1]).unwrap();
rx.recv();
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
s.write([2]).unwrap();
rx.recv();
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
});
let mut s1 = acceptor.accept().unwrap();
let s2 = s1.clone();
let (done, rx) = channel();
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
spawn(proc() {
let mut s2 = s2;
let mut buf = [0, 0];
s2.read(buf).unwrap();
tx2.send(());
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
done.send(());
});
let mut buf = [0, 0];
s1.read(buf).unwrap();
tx1.send(());
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
rx.recv();
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
})
iotest!(fn tcp_clone_two_write() {
let addr = next_test_ip4();
let mut acceptor = TcpListener::bind(addr).listen();
spawn(proc() {
let mut s = TcpStream::connect(addr);
let mut buf = [0, 1];
s.read(buf).unwrap();
s.read(buf).unwrap();
});
let mut s1 = acceptor.accept().unwrap();
let s2 = s1.clone();
let (done, rx) = channel();
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
spawn(proc() {
let mut s2 = s2;
s2.write([1]).unwrap();
done.send(());
});
s1.write([2]).unwrap();
rx.recv();
Implement clone() for TCP/UDP/Unix sockets This is part of the overall strategy I would like to take when approaching issue #11165. The only two I/O objects that reasonably want to be "split" are the network stream objects. Everything else can be "split" by just creating another version. The initial idea I had was the literally split the object into a reader and a writer half, but that would just introduce lots of clutter with extra interfaces that were a little unnnecssary, or it would return a ~Reader and a ~Writer which means you couldn't access things like the remote peer name or local socket name. The solution I found to be nicer was to just clone the stream itself. The clone is just a clone of the handle, nothing fancy going on at the kernel level. Conceptually I found this very easy to wrap my head around (everything else supports clone()), and it solved the "split" problem at the same time. The cloning support is pretty specific per platform/lib combination: * native/win32 - uses some specific WSA apis to clone the SOCKET handle * native/unix - uses dup() to get another file descriptor * green/all - This is where things get interesting. When we support full clones of a handle, this implies that we're allowing simultaneous writes and reads to happen. It turns out that libuv doesn't support two simultaneous reads or writes of the same object. It does support *one* read and *one* write at the same time, however. Some extra infrastructure was added to just block concurrent writers/readers until the previous read/write operation was completed. I've added tests to the tcp/unix modules to make sure that this functionality is supported everywhere.
2014-01-22 19:32:16 -08:00
})
iotest!(fn shutdown_smoke() {
use rt::rtio::RtioTcpStream;
let addr = next_test_ip4();
let a = TcpListener::bind(addr).unwrap().listen();
spawn(proc() {
let mut a = a;
let mut c = a.accept().unwrap();
assert_eq!(c.read_to_end(), Ok(vec!()));
c.write([1]).unwrap();
});
let mut s = TcpStream::connect(addr).unwrap();
assert!(s.obj.close_write().is_ok());
assert!(s.write([1]).is_err());
assert_eq!(s.read_to_end(), Ok(vec!(1)));
})
iotest!(fn accept_timeout() {
let addr = next_test_ip4();
let mut a = TcpListener::bind(addr).unwrap().listen().unwrap();
a.set_timeout(Some(10));
// Make sure we time out once and future invocations also time out
let err = a.accept().err().unwrap();
assert_eq!(err.kind, TimedOut);
let err = a.accept().err().unwrap();
assert_eq!(err.kind, TimedOut);
// Also make sure that even though the timeout is expired that we will
// continue to receive any pending connections.
let l = TcpStream::connect(addr).unwrap();
for i in range(0, 1001) {
match a.accept() {
Ok(..) => break,
Err(ref e) if e.kind == TimedOut => {}
Err(e) => fail!("error: {}", e),
}
if i == 1000 { fail!("should have a pending connection") }
}
drop(l);
// Unset the timeout and make sure that this always blocks.
a.set_timeout(None);
spawn(proc() {
drop(TcpStream::connect(addr));
});
a.accept().unwrap();
})
}