1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use crate::io::{self, prelude::*};

use axnet::{SocketAddr, TcpSocket};

/// A TCP stream between a local and a remote socket.
pub struct TcpStream {
    socket: TcpSocket,
}

/// A TCP socket server, listening for connections.
pub struct TcpListener {
    socket: TcpSocket,
}

impl TcpStream {
    /// Opens a TCP connection to a remote host.
    pub fn connect(addr: SocketAddr) -> io::Result<Self> {
        let mut socket = TcpSocket::new();
        socket.connect(addr)?;
        Ok(Self { socket })
    }

    /// Returns the socket address of the local half of this TCP connection.
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.socket.local_addr()
    }

    /// Returns the socket address of the remote peer of this TCP connection.
    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        self.socket.peer_addr()
    }

    /// Shuts down the connection.
    pub fn shutdown(&self) -> io::Result {
        self.socket.shutdown()
    }
}

impl Read for TcpStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.socket.recv(buf)
    }
}

impl Write for TcpStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.socket.send(buf)
    }

    fn flush(&mut self) -> io::Result {
        Ok(())
    }
}

impl TcpListener {
    /// Creates a new `TcpListener` which will be bound to the specified
    /// address.
    pub fn bind(addr: SocketAddr) -> io::Result<Self> {
        let mut socket = TcpSocket::new();
        socket.bind(addr)?;
        socket.listen()?;
        Ok(Self { socket })
    }

    /// Returns the local socket address of this listener.
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.socket.local_addr()
    }

    /// Accept a new incoming connection from this listener.
    ///
    /// This function will block the calling thread until a new TCP connection
    /// is established. When established, the corresponding [`TcpStream`] and the
    /// remote peer's address will be returned.
    pub fn accept(&mut self) -> io::Result<(TcpStream, SocketAddr)> {
        let socket = self.socket.accept()?;
        let addr = socket.peer_addr()?;
        Ok((TcpStream { socket }, addr))
    }
}