Skip to main content

TcpSocket

Struct TcpSocket 

Source
pub struct TcpSocket(/* private fields */);
Expand description

A TCP stream between a local and a remote socket.

After creating a TcpSocket by either connecting to a remote host or accepting a connection on a TcpSocket, data can be transmitted by reading and writing to it.

The connection will be closed when the value is dropped. The reading and writing portions of the connection can also be shut down individually with the shutdown method.

The Transmission Control Protocol is specified in IETF RFC 793.

§Examples

use std::io::prelude::*;
use psocket::TcpSocket;

{
    let mut stream = TcpSocket::connect("127.0.0.1:34254").unwrap();

    // ignore the Result
    let _ = stream.write(&[1]);
    let _ = stream.read(&mut [0; 128]); // ignore here too
} // the stream is closed here

Implementations§

Source§

impl TcpSocket

Source

pub fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpSocket>

Opens a TCP connection to a remote host.

addr is an address of the remote host. Anything which implements ToSocketAddrs trait can be supplied for the address; see this trait documentation for concrete examples.

If addr yields multiple addresses, connect will be attempted with each of the addresses until a connection is successful. If none of the addresses result in a successful connection, the error returned from the last connection attempt (the last address) is returned.

§Examples

Open a TCP connection to 127.0.0.1:8080:

use psocket::TcpSocket;

if let Ok(stream) = TcpSocket::connect("127.0.0.1:8080") {
    println!("Connected to the server!");
} else {
    println!("Couldn't connect to server...");
}

Open a TCP connection to 127.0.0.1:8080. If the connection fails, open a TCP connection to 127.0.0.1:8081:

use psocket::{SocketAddr, TcpSocket};

let addrs = [
    SocketAddr::from(([127, 0, 0, 1], 8080)),
    SocketAddr::from(([127, 0, 0, 1], 8081)),
];
if let Ok(stream) = TcpSocket::connect(&addrs[..]) {
    println!("Connected to the server!");
} else {
    println!("Couldn't connect to server...");
}
Examples found in repository?
examples/test.rs (line 15)
9fn main() {
10
11    // bind and drop a socket to track down a "probably unassigned" port
12    let listener = TcpSocket::bind("127.0.0.1:1234").unwrap();
13    let addr = listener.local_addr().unwrap();
14    
15    let mut stream = TcpSocket::connect(&("localhost", addr.port())).expect("connect error");
16    stream.set_read_timeout(Some(Duration::from_millis(1000))).expect("set read timeout error");
17
18    let mut other_end = listener.accept().unwrap().0;
19    other_end.write_all(b"hello world").expect("write error");
20
21    let mut buf = [0; 11];
22    stream.read(&mut buf).expect("read error");
23    assert_eq!(b"hello world", &buf[..]);
24
25    let start = Instant::now();
26    let kind = stream.read(&mut buf).err().expect("expected error").kind();
27    assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
28    assert!(start.elapsed() > Duration::from_millis(400));
29    drop(listener);
30
31    // socket.set_liner(true, 10);
32    // assert_eq!((true, 10), socket.liner().unwrap());
33
34    // socket.set_recv_size(20480);
35    // assert_eq!(20480, socket.recv_size().unwrap());
36    
37    // socket.set_send_size(40960);
38    // assert_eq!(40960, socket.send_size().unwrap());
39    
40    // let mut new_socket = socket.clone();
41    // assert_eq!(20480, new_socket.recv_size().unwrap());
42    
43    // new_socket.unlink();    
44    // drop(new_socket);
45    // assert_eq!(20480, socket.recv_size().unwrap());
46    
47    // let new_socket = socket.clone();
48    // drop(new_socket);
49    // assert!(socket.recv_size().is_err());
50
51    // println!("finish");
52    // let addr = "www.baidu.com:80".to_socket_addrs().unwrap().next().unwrap();
53    // // drop(socket);
54
55    // println!("addr = {:?}", addr);
56
57    // let timeout = Duration::from_secs(1);
58    // let mut e = TcpSocket::connect_asyn(&addr).unwrap();
59    // loop {
60    //     println!("e = {:?}", e);
61    //     println!("e.check_ready() = {:?}", e.check_ready().unwrap());
62    //     if e.is_ready() {
63    //         break;
64    //     }
65    // }
66    // println!("e = {:?}", e);
67    // assert!(e.kind() == io::ErrorKind::ConnectionRefused ||
68    //         e.kind() == io::ErrorKind::TimedOut ||
69    //         e.kind() == io::ErrorKind::Other,
70    //         "bad error: {} {:?}", e, e.kind());
71}
Source

pub fn s_connect<A: ToSocketAddrs>(&self, addr: A) -> Result<()>

Source

pub fn connect_timeout( addr: &SocketAddr, timeout: Duration, ) -> Result<TcpSocket>

Opens a TCP connection to a remote host with a timeout.

Unlike connect, connect_timeout takes a single SocketAddr since timeout must be applied to individual addresses.

It is an error to pass a zero Duration to this function.

Unlike other methods on TcpSocket, this does not correspond to a single system call. It instead calls connect in nonblocking mode and then uses an OS-specific mechanism to await the completion of the connection request.

Source

pub fn s_connect_timeout( &self, addr: &SocketAddr, timeout: Duration, ) -> Result<()>

Source

pub fn connect_asyn(addr: &SocketAddr) -> Result<TcpSocket>

Opens a TCP connection to a remote host with asyn. It will return immediately but the stream status is not ok, when you want to use it, must call check_ready to check ok

Source

pub fn s_connect_asyn(&self, addr: &SocketAddr) -> Result<()>

Source

pub fn as_raw_socket(&self) -> SOCKET

Source

pub fn new_by_fd(fd: SOCKET) -> Result<TcpSocket>

new by the socket fd, it will always set ready ok it will not a valid socket, when fd set -1

Source

pub fn new_invalid() -> Result<TcpSocket>

Source

pub fn is_valid(&self) -> bool

check the socket is valid.

Source

pub fn is_ready(&self) -> bool

check the socket status is ready.

Source

pub fn set_ready(&self, ready: bool)

set socket ready status manual.

Source

pub fn is_close(&self) -> bool

Source

pub fn close(&self)

Source

pub fn check_ready(&self) -> Result<bool>

check socket ready status, when you connect remote host by asyn.

Source

pub fn peer_addr(&self) -> Result<SocketAddr>

Returns the socket address of the remote peer of this TCP connection.

§Examples
use psocket::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpSocket};

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
assert_eq!(stream.peer_addr().unwrap(),
           SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
Source

pub fn set_peer_addr(&mut self, addr: SocketAddr)

Source

pub fn local_addr(&self) -> Result<SocketAddr>

Returns the socket address of the local half of this TCP connection.

§Examples
use psocket::{IpAddr, Ipv4Addr, TcpSocket};

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
assert_eq!(stream.local_addr().unwrap().ip(),
           IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
Examples found in repository?
examples/test.rs (line 13)
9fn main() {
10
11    // bind and drop a socket to track down a "probably unassigned" port
12    let listener = TcpSocket::bind("127.0.0.1:1234").unwrap();
13    let addr = listener.local_addr().unwrap();
14    
15    let mut stream = TcpSocket::connect(&("localhost", addr.port())).expect("connect error");
16    stream.set_read_timeout(Some(Duration::from_millis(1000))).expect("set read timeout error");
17
18    let mut other_end = listener.accept().unwrap().0;
19    other_end.write_all(b"hello world").expect("write error");
20
21    let mut buf = [0; 11];
22    stream.read(&mut buf).expect("read error");
23    assert_eq!(b"hello world", &buf[..]);
24
25    let start = Instant::now();
26    let kind = stream.read(&mut buf).err().expect("expected error").kind();
27    assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
28    assert!(start.elapsed() > Duration::from_millis(400));
29    drop(listener);
30
31    // socket.set_liner(true, 10);
32    // assert_eq!((true, 10), socket.liner().unwrap());
33
34    // socket.set_recv_size(20480);
35    // assert_eq!(20480, socket.recv_size().unwrap());
36    
37    // socket.set_send_size(40960);
38    // assert_eq!(40960, socket.send_size().unwrap());
39    
40    // let mut new_socket = socket.clone();
41    // assert_eq!(20480, new_socket.recv_size().unwrap());
42    
43    // new_socket.unlink();    
44    // drop(new_socket);
45    // assert_eq!(20480, socket.recv_size().unwrap());
46    
47    // let new_socket = socket.clone();
48    // drop(new_socket);
49    // assert!(socket.recv_size().is_err());
50
51    // println!("finish");
52    // let addr = "www.baidu.com:80".to_socket_addrs().unwrap().next().unwrap();
53    // // drop(socket);
54
55    // println!("addr = {:?}", addr);
56
57    // let timeout = Duration::from_secs(1);
58    // let mut e = TcpSocket::connect_asyn(&addr).unwrap();
59    // loop {
60    //     println!("e = {:?}", e);
61    //     println!("e.check_ready() = {:?}", e.check_ready().unwrap());
62    //     if e.is_ready() {
63    //         break;
64    //     }
65    // }
66    // println!("e = {:?}", e);
67    // assert!(e.kind() == io::ErrorKind::ConnectionRefused ||
68    //         e.kind() == io::ErrorKind::TimedOut ||
69    //         e.kind() == io::ErrorKind::Other,
70    //         "bad error: {} {:?}", e, e.kind());
71}
Source

pub fn set_local_addr(&mut self, addr: SocketAddr)

Source

pub fn shutdown(&self, how: Shutdown) -> Result<()>

Shuts down the read, write, or both halves of this connection.

This function will cause all pending and future I/O on the specified portions to return immediately with an appropriate value (see the documentation of Shutdown).

§Platform-specific behavior

Calling this function multiple times may result in different behavior, depending on the operating system. On Linux, the second call will return Ok(()), but on macOS, it will return ErrorKind::NotConnected. This may change in the future.

§Examples
use psocket::{Shutdown, TcpSocket};

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.shutdown(Shutdown::Both).expect("shutdown call failed");
Source

pub fn try_clone(&self) -> Result<TcpSocket>

Creates a new independently owned handle to the underlying socket.

The returned TcpSocket is a reference to the same stream that this object references. Both handles will read and write the same stream of data, and options set on one stream will be propagated to the other stream.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
let stream_clone = stream.try_clone().expect("clone failed...");
Source

pub fn set_read_timeout(&self, dur: Option<Duration>) -> Result<()>

Sets the read timeout to the timeout specified.

If the value specified is None, then read calls will block indefinitely. It is an error to pass the zero Duration to this method.

§Note

Platforms may return a different error code whenever a read times out as a result of setting this option. For example Unix typically returns an error of the kind WouldBlock, but Windows may return TimedOut.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_read_timeout(None).expect("set_read_timeout call failed");
Examples found in repository?
examples/test.rs (line 16)
9fn main() {
10
11    // bind and drop a socket to track down a "probably unassigned" port
12    let listener = TcpSocket::bind("127.0.0.1:1234").unwrap();
13    let addr = listener.local_addr().unwrap();
14    
15    let mut stream = TcpSocket::connect(&("localhost", addr.port())).expect("connect error");
16    stream.set_read_timeout(Some(Duration::from_millis(1000))).expect("set read timeout error");
17
18    let mut other_end = listener.accept().unwrap().0;
19    other_end.write_all(b"hello world").expect("write error");
20
21    let mut buf = [0; 11];
22    stream.read(&mut buf).expect("read error");
23    assert_eq!(b"hello world", &buf[..]);
24
25    let start = Instant::now();
26    let kind = stream.read(&mut buf).err().expect("expected error").kind();
27    assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
28    assert!(start.elapsed() > Duration::from_millis(400));
29    drop(listener);
30
31    // socket.set_liner(true, 10);
32    // assert_eq!((true, 10), socket.liner().unwrap());
33
34    // socket.set_recv_size(20480);
35    // assert_eq!(20480, socket.recv_size().unwrap());
36    
37    // socket.set_send_size(40960);
38    // assert_eq!(40960, socket.send_size().unwrap());
39    
40    // let mut new_socket = socket.clone();
41    // assert_eq!(20480, new_socket.recv_size().unwrap());
42    
43    // new_socket.unlink();    
44    // drop(new_socket);
45    // assert_eq!(20480, socket.recv_size().unwrap());
46    
47    // let new_socket = socket.clone();
48    // drop(new_socket);
49    // assert!(socket.recv_size().is_err());
50
51    // println!("finish");
52    // let addr = "www.baidu.com:80".to_socket_addrs().unwrap().next().unwrap();
53    // // drop(socket);
54
55    // println!("addr = {:?}", addr);
56
57    // let timeout = Duration::from_secs(1);
58    // let mut e = TcpSocket::connect_asyn(&addr).unwrap();
59    // loop {
60    //     println!("e = {:?}", e);
61    //     println!("e.check_ready() = {:?}", e.check_ready().unwrap());
62    //     if e.is_ready() {
63    //         break;
64    //     }
65    // }
66    // println!("e = {:?}", e);
67    // assert!(e.kind() == io::ErrorKind::ConnectionRefused ||
68    //         e.kind() == io::ErrorKind::TimedOut ||
69    //         e.kind() == io::ErrorKind::Other,
70    //         "bad error: {} {:?}", e, e.kind());
71}
Source

pub fn set_write_timeout(&self, dur: Option<Duration>) -> Result<()>

Sets the write timeout to the timeout specified.

If the value specified is None, then write calls will block indefinitely. It is an error to pass the zero Duration to this method.

§Note

Platforms may return a different error code whenever a write times out as a result of setting this option. For example Unix typically returns an error of the kind WouldBlock, but Windows may return TimedOut.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_write_timeout(None).expect("set_write_timeout call failed");
Source

pub fn read_timeout(&self) -> Result<Option<Duration>>

Returns the read timeout of this socket.

If the timeout is None, then read calls will block indefinitely.

§Note

Some platforms do not provide access to the current timeout.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_read_timeout(None).expect("set_read_timeout call failed");
assert_eq!(stream.read_timeout().unwrap(), None);
Source

pub fn write_timeout(&self) -> Result<Option<Duration>>

Returns the write timeout of this socket.

If the timeout is None, then write calls will block indefinitely.

§Note

Some platforms do not provide access to the current timeout.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_write_timeout(None).expect("set_write_timeout call failed");
assert_eq!(stream.write_timeout().unwrap(), None);
Source

pub fn peek(&self, buf: &mut [u8]) -> Result<usize>

Receives data on the socket from the remote address to which it is connected, without removing that data from the queue. On success, returns the number of bytes peeked.

Successive calls return the same data. This is accomplished by passing MSG_PEEK as a flag to the underlying recv system call.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8000")
                       .expect("couldn't bind to address");
let mut buf = [0; 10];
let len = stream.peek(&mut buf).expect("peek failed");
Source

pub fn set_nodelay(&self, nodelay: bool) -> Result<()>

Sets the value of the TCP_NODELAY option on this socket.

If set, this option disables the Nagle algorithm. This means that segments are always sent as soon as possible, even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount to send out, thereby avoiding the frequent sending of small packets.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_nodelay(true).expect("set_nodelay call failed");
Source

pub fn nodelay(&self) -> Result<bool>

Gets the value of the TCP_NODELAY option on this socket.

For more information about this option, see set_nodelay.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_nodelay(true).expect("set_nodelay call failed");
assert_eq!(stream.nodelay().unwrap_or(false), true);
Source

pub fn set_ttl(&self, ttl: u32) -> Result<()>

Sets the value for the IP_TTL option on this socket.

This value sets the time-to-live field that is used in every packet sent from this socket.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_ttl(100).expect("set_ttl call failed");
Source

pub fn ttl(&self) -> Result<u32>

Gets the value of the IP_TTL option for this socket.

For more information about this option, see set_ttl.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_ttl(100).expect("set_ttl call failed");
assert_eq!(stream.ttl().unwrap_or(0), 100);
Source

pub fn take_error(&self) -> Result<Option<Error>>

Get the value of the SO_ERROR option on this socket.

This will retrieve the stored error in the underlying socket, clearing the field in the process. This can be useful for checking errors between calls.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.take_error().expect("No error was expected...");
Source

pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>

Moves this TCP stream into or out of nonblocking mode.

On Unix this corresponds to calling fcntl, and on Windows this corresponds to calling ioctlsocket.

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_nonblocking(true).expect("set_nonblocking call failed");
Source

pub fn is_nonblocking(&self) -> bool

The method measure the socket is nonblocking

§Examples
use psocket::TcpSocket;

let stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_nonblocking(true).expect("set_nonblocking call failed");
assert!(stream.is_nonblocking());
Source

pub fn set_liner(&self, enable: bool, time: u16) -> Result<()>

Moves this TCP stream into or out of liner mode. If set disable when close the stream, it return immediately but may miss data send in kernel cache, If set enable when close the stream, the kernel cache will send by kernel until timeout time unit is second

§Examples
use psocket::TcpSocket;

let mut stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_liner(true, 10).expect("set_liner call failed");
assert_eq!((true, 10), stream.liner().unwrap());
Source

pub fn liner(&self) -> Result<(bool, u16)>

The method get the socket liner info

Source

pub fn set_recv_size(&self, size: u32) -> Result<()>

The Method is set stream recv size kernel cache size. When in linux it will double the size you set, so inner already div double. It’s size will limit by linux limit size set the unit is byte

§Examples
use std::cmp;
use psocket::TcpSocket;

let mut stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_recv_size(20480).expect("set_recv_size call failed");
assert!(stream.recv_size().unwrap() <= 20480);
Source

pub fn recv_size(&self) -> Result<u32>

The Method is get stream recv size kernel cache size.

Source

pub fn set_send_size(&self, size: u32) -> Result<()>

The Method is set stream send size kernel cache size. When in linux it will double the size you set, so inner already div double. It’s size will limit by linux limit size set the unit is byte

§Examples
use std::cmp;
use psocket::TcpSocket;

let mut stream = TcpSocket::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_send_size(20480).expect("set_recv_size call failed");
assert!(stream.send_size().unwrap() <= 20480);
Source

pub fn send_size(&self) -> Result<u32>

The Method is get stream send size kernel cache size.

Source

pub fn set_reuse_addr(&self) -> Result<()>

The Method is set tcp stream SO_REUSEADDR.

Source

pub fn set_reuse_port(&self) -> Result<()>

The Method is set tcp stream SO_REUSEPORT.

Source

pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<TcpSocket>

Creates a new TcpSocket which will be bound to the specified address.

The returned listener is ready for accepting connections.

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 local_addr method.

The address type can be any implementor of ToSocketAddrs trait. See its documentation for concrete examples.

If addr yields multiple addresses, bind will be attempted with each of the addresses until one succeeds and returns the listener. If none of the addresses succeed in creating a listener, the error returned from the last attempt (the last address) is returned.

§Examples

Create a TCP listener bound to 127.0.0.1:80:

use psocket::TcpSocket;

let listener = TcpSocket::bind("127.0.0.1:80").unwrap();

Create a TCP listener bound to 127.0.0.1:80. If that fails, create a TCP listener bound to 127.0.0.1:443:

use psocket::{SocketAddr, TcpSocket};

let addrs = [
    SocketAddr::from(([127, 0, 0, 1], 80)),
    SocketAddr::from(([127, 0, 0, 1], 443)),
];
let listener = TcpSocket::bind(&addrs[..]).unwrap();
Examples found in repository?
examples/test.rs (line 12)
9fn main() {
10
11    // bind and drop a socket to track down a "probably unassigned" port
12    let listener = TcpSocket::bind("127.0.0.1:1234").unwrap();
13    let addr = listener.local_addr().unwrap();
14    
15    let mut stream = TcpSocket::connect(&("localhost", addr.port())).expect("connect error");
16    stream.set_read_timeout(Some(Duration::from_millis(1000))).expect("set read timeout error");
17
18    let mut other_end = listener.accept().unwrap().0;
19    other_end.write_all(b"hello world").expect("write error");
20
21    let mut buf = [0; 11];
22    stream.read(&mut buf).expect("read error");
23    assert_eq!(b"hello world", &buf[..]);
24
25    let start = Instant::now();
26    let kind = stream.read(&mut buf).err().expect("expected error").kind();
27    assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
28    assert!(start.elapsed() > Duration::from_millis(400));
29    drop(listener);
30
31    // socket.set_liner(true, 10);
32    // assert_eq!((true, 10), socket.liner().unwrap());
33
34    // socket.set_recv_size(20480);
35    // assert_eq!(20480, socket.recv_size().unwrap());
36    
37    // socket.set_send_size(40960);
38    // assert_eq!(40960, socket.send_size().unwrap());
39    
40    // let mut new_socket = socket.clone();
41    // assert_eq!(20480, new_socket.recv_size().unwrap());
42    
43    // new_socket.unlink();    
44    // drop(new_socket);
45    // assert_eq!(20480, socket.recv_size().unwrap());
46    
47    // let new_socket = socket.clone();
48    // drop(new_socket);
49    // assert!(socket.recv_size().is_err());
50
51    // println!("finish");
52    // let addr = "www.baidu.com:80".to_socket_addrs().unwrap().next().unwrap();
53    // // drop(socket);
54
55    // println!("addr = {:?}", addr);
56
57    // let timeout = Duration::from_secs(1);
58    // let mut e = TcpSocket::connect_asyn(&addr).unwrap();
59    // loop {
60    //     println!("e = {:?}", e);
61    //     println!("e.check_ready() = {:?}", e.check_ready().unwrap());
62    //     if e.is_ready() {
63    //         break;
64    //     }
65    // }
66    // println!("e = {:?}", e);
67    // assert!(e.kind() == io::ErrorKind::ConnectionRefused ||
68    //         e.kind() == io::ErrorKind::TimedOut ||
69    //         e.kind() == io::ErrorKind::Other,
70    //         "bad error: {} {:?}", e, e.kind());
71}
Source

pub fn bind_exist<A: ToSocketAddrs>(&self, addr: A) -> Result<()>

Bind in exist socket, you can set the prop before you bind

Source

pub fn accept(&self) -> Result<(TcpSocket, SocketAddr)>

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 TcpSocket and the remote peer’s address will be returned.

§Examples
use psocket::TcpSocket;

let listener = TcpSocket::bind("127.0.0.1:8080").unwrap();
match listener.accept() {
    Ok((_socket, addr)) => println!("new client: {:?}", addr),
    Err(e) => println!("couldn't get client: {:?}", e),
}
Examples found in repository?
examples/test.rs (line 18)
9fn main() {
10
11    // bind and drop a socket to track down a "probably unassigned" port
12    let listener = TcpSocket::bind("127.0.0.1:1234").unwrap();
13    let addr = listener.local_addr().unwrap();
14    
15    let mut stream = TcpSocket::connect(&("localhost", addr.port())).expect("connect error");
16    stream.set_read_timeout(Some(Duration::from_millis(1000))).expect("set read timeout error");
17
18    let mut other_end = listener.accept().unwrap().0;
19    other_end.write_all(b"hello world").expect("write error");
20
21    let mut buf = [0; 11];
22    stream.read(&mut buf).expect("read error");
23    assert_eq!(b"hello world", &buf[..]);
24
25    let start = Instant::now();
26    let kind = stream.read(&mut buf).err().expect("expected error").kind();
27    assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
28    assert!(start.elapsed() > Duration::from_millis(400));
29    drop(listener);
30
31    // socket.set_liner(true, 10);
32    // assert_eq!((true, 10), socket.liner().unwrap());
33
34    // socket.set_recv_size(20480);
35    // assert_eq!(20480, socket.recv_size().unwrap());
36    
37    // socket.set_send_size(40960);
38    // assert_eq!(40960, socket.send_size().unwrap());
39    
40    // let mut new_socket = socket.clone();
41    // assert_eq!(20480, new_socket.recv_size().unwrap());
42    
43    // new_socket.unlink();    
44    // drop(new_socket);
45    // assert_eq!(20480, socket.recv_size().unwrap());
46    
47    // let new_socket = socket.clone();
48    // drop(new_socket);
49    // assert!(socket.recv_size().is_err());
50
51    // println!("finish");
52    // let addr = "www.baidu.com:80".to_socket_addrs().unwrap().next().unwrap();
53    // // drop(socket);
54
55    // println!("addr = {:?}", addr);
56
57    // let timeout = Duration::from_secs(1);
58    // let mut e = TcpSocket::connect_asyn(&addr).unwrap();
59    // loop {
60    //     println!("e = {:?}", e);
61    //     println!("e.check_ready() = {:?}", e.check_ready().unwrap());
62    //     if e.is_ready() {
63    //         break;
64    //     }
65    // }
66    // println!("e = {:?}", e);
67    // assert!(e.kind() == io::ErrorKind::ConnectionRefused ||
68    //         e.kind() == io::ErrorKind::TimedOut ||
69    //         e.kind() == io::ErrorKind::Other,
70    //         "bad error: {} {:?}", e, e.kind());
71}
Source

pub fn incoming(&self) -> Incoming<'_>

Returns an iterator over the connections being received on this listener.

The returned iterator will never return None and will also not yield the peer’s SocketAddr structure. Iterating over it is equivalent to calling accept in a loop.

§Examples
use psocket::TcpSocket;

let listener = TcpSocket::bind("127.0.0.1:80").unwrap();

for stream in listener.incoming() {
    match stream {
        Ok(stream) => {
            println!("new client!");
        }
        Err(e) => { /* connection failed */ }
    }
}

It will unclose the tcp socket. When call this method, the tcp socket will be invalid, can’t do anything, it need be call in clone func or new_by_fd func

Source

pub fn new_v4() -> Result<TcpSocket>

Constructs a new TcpBuilder with the AF_INET domain, the SOCK_STREAM type, and with a protocol argument of 0.

Source

pub fn new_v6() -> Result<TcpSocket>

Constructs a new TcpBuilder with the AF_INET6 domain, the SOCK_STREAM type, and with a protocol argument of 0.

Source

pub fn convert_to_stream(self) -> TcpStream

Source

pub fn convert_to_listener(self) -> TcpListener

Source

pub fn from_stream(tcp: TcpStream) -> TcpSocket

Source

pub fn from_listener(listen: TcpListener) -> TcpSocket

Trait Implementations§

Source§

impl Clone for TcpSocket

Source§

fn clone(&self) -> TcpSocket

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TcpSocket

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Read for TcpSocket

Source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
1.36.0 · Source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · Source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · Source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · Source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Reads the exact number of bytes required to fill buf. Read more
Source§

fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact( &mut self, cursor: BorrowedCursor<'_, u8>, ) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
Source§

fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>
where Self: Sized,

🔬This is a nightly-only experimental API. (read_array)
Read and return a fixed array of bytes from this source. Read more
Source§

fn read_le<T>(&mut self) -> Result<T, Error>
where T: FromEndianBytes, Self: Sized,

🔬This is a nightly-only experimental API. (read_le)
Read and return a type (e.g. an integer) in little-endian order. Read more
Source§

fn read_be<T>(&mut self) -> Result<T, Error>
where T: FromEndianBytes, Self: Sized,

🔬This is a nightly-only experimental API. (read_le)
Read and return a type (e.g. an integer) in big-endian order. Read more
Source§

impl<'a> Read for &'a TcpSocket

Source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
1.36.0 · Source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · Source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · Source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · Source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Reads the exact number of bytes required to fill buf. Read more
Source§

fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact( &mut self, cursor: BorrowedCursor<'_, u8>, ) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
Source§

fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>
where Self: Sized,

🔬This is a nightly-only experimental API. (read_array)
Read and return a fixed array of bytes from this source. Read more
Source§

fn read_le<T>(&mut self) -> Result<T, Error>
where T: FromEndianBytes, Self: Sized,

🔬This is a nightly-only experimental API. (read_le)
Read and return a type (e.g. an integer) in little-endian order. Read more
Source§

fn read_be<T>(&mut self) -> Result<T, Error>
where T: FromEndianBytes, Self: Sized,

🔬This is a nightly-only experimental API. (read_le)
Read and return a type (e.g. an integer) in big-endian order. Read more
Source§

impl Write for TcpSocket

Source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Writes a buffer into this writer, returning how many bytes were written. Read more
Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more
Source§

impl<'a> Write for &'a TcpSocket

Source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Writes a buffer into this writer, returning how many bytes were written. Read more
Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.