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 hereImplementations§
Source§impl TcpSocket
impl TcpSocket
Sourcepub fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpSocket>
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?
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}pub fn s_connect<A: ToSocketAddrs>(&self, addr: A) -> Result<()>
Sourcepub fn connect_timeout(
addr: &SocketAddr,
timeout: Duration,
) -> Result<TcpSocket>
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.
pub fn s_connect_timeout( &self, addr: &SocketAddr, timeout: Duration, ) -> Result<()>
Sourcepub fn connect_asyn(addr: &SocketAddr) -> Result<TcpSocket>
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
pub fn s_connect_asyn(&self, addr: &SocketAddr) -> Result<()>
pub fn as_raw_socket(&self) -> SOCKET
Sourcepub fn new_by_fd(fd: SOCKET) -> Result<TcpSocket>
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
pub fn new_invalid() -> Result<TcpSocket>
pub fn is_close(&self) -> bool
pub fn close(&self)
Sourcepub fn check_ready(&self) -> Result<bool>
pub fn check_ready(&self) -> Result<bool>
check socket ready status, when you connect remote host by asyn.
Sourcepub fn peer_addr(&self) -> Result<SocketAddr>
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)));pub fn set_peer_addr(&mut self, addr: SocketAddr)
Sourcepub fn local_addr(&self) -> Result<SocketAddr>
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?
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}pub fn set_local_addr(&mut self, addr: SocketAddr)
Sourcepub fn shutdown(&self, how: Shutdown) -> Result<()>
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");Sourcepub fn try_clone(&self) -> Result<TcpSocket>
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...");Sourcepub fn set_read_timeout(&self, dur: Option<Duration>) -> Result<()>
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?
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}Sourcepub fn set_write_timeout(&self, dur: Option<Duration>) -> Result<()>
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");Sourcepub fn read_timeout(&self) -> Result<Option<Duration>>
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);Sourcepub fn write_timeout(&self) -> Result<Option<Duration>>
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);Sourcepub fn peek(&self, buf: &mut [u8]) -> Result<usize>
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");Sourcepub fn set_nodelay(&self, nodelay: bool) -> Result<()>
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");Sourcepub fn nodelay(&self) -> Result<bool>
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);Sourcepub fn set_ttl(&self, ttl: u32) -> Result<()>
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");Sourcepub fn ttl(&self) -> Result<u32>
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);Sourcepub fn take_error(&self) -> Result<Option<Error>>
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...");Sourcepub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>
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");Sourcepub fn is_nonblocking(&self) -> bool
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());Sourcepub fn set_liner(&self, enable: bool, time: u16) -> Result<()>
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());Sourcepub fn set_recv_size(&self, size: u32) -> Result<()>
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);Sourcepub fn set_send_size(&self, size: u32) -> Result<()>
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);Sourcepub fn set_reuse_addr(&self) -> Result<()>
pub fn set_reuse_addr(&self) -> Result<()>
The Method is set tcp stream SO_REUSEADDR.
Sourcepub fn set_reuse_port(&self) -> Result<()>
pub fn set_reuse_port(&self) -> Result<()>
The Method is set tcp stream SO_REUSEPORT.
Sourcepub fn bind<A: ToSocketAddrs>(addr: A) -> Result<TcpSocket>
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?
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}Sourcepub fn bind_exist<A: ToSocketAddrs>(&self, addr: A) -> Result<()>
pub fn bind_exist<A: ToSocketAddrs>(&self, addr: A) -> Result<()>
Bind in exist socket, you can set the prop before you bind
Sourcepub fn accept(&self) -> Result<(TcpSocket, SocketAddr)>
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?
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}Sourcepub fn incoming(&self) -> Incoming<'_> ⓘ
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 */ }
}
}Sourcepub fn unlink(self) -> Result<()>
pub fn unlink(self) -> Result<()>
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
Sourcepub fn new_v4() -> Result<TcpSocket>
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.
Sourcepub fn new_v6() -> Result<TcpSocket>
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.
pub fn convert_to_stream(self) -> TcpStream
pub fn convert_to_listener(self) -> TcpListener
pub fn from_stream(tcp: TcpStream) -> TcpSocket ⓘ
pub fn from_listener(listen: TcpListener) -> TcpSocket ⓘ
Trait Implementations§
Source§impl Read for TcpSocket
impl Read for TcpSocket
Source§fn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
1.36.0 · Source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read, except that it reads into a slice of buffers. Read moreSource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector)1.0.0 · Source§fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
buf. Read more1.0.0 · Source§fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
buf. Read more1.6.0 · Source§fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
buf. Read moreSource§fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>
fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>
read_buf)Source§fn read_buf_exact(
&mut self,
cursor: BorrowedCursor<'_, u8>,
) -> Result<(), Error>
fn read_buf_exact( &mut self, cursor: BorrowedCursor<'_, u8>, ) -> Result<(), Error>
read_buf)cursor. Read more1.0.0 · Source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read. Read more1.0.0 · Source§fn chain<R>(self, next: R) -> Chain<Self, R>
fn chain<R>(self, next: R) -> Chain<Self, R>
1.0.0 · Source§fn take(self, limit: u64) -> Take<Self>where
Self: Sized,
fn take(self, limit: u64) -> Take<Self>where
Self: Sized,
limit bytes from it. Read moreSource§fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>where
Self: Sized,
fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>where
Self: Sized,
read_array)Source§impl<'a> Read for &'a TcpSocket
impl<'a> Read for &'a TcpSocket
Source§fn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
1.36.0 · Source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read, except that it reads into a slice of buffers. Read moreSource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector)1.0.0 · Source§fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
buf. Read more1.0.0 · Source§fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
buf. Read more1.6.0 · Source§fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
buf. Read moreSource§fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>
fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>
read_buf)Source§fn read_buf_exact(
&mut self,
cursor: BorrowedCursor<'_, u8>,
) -> Result<(), Error>
fn read_buf_exact( &mut self, cursor: BorrowedCursor<'_, u8>, ) -> Result<(), Error>
read_buf)cursor. Read more1.0.0 · Source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read. Read more1.0.0 · Source§fn chain<R>(self, next: R) -> Chain<Self, R>
fn chain<R>(self, next: R) -> Chain<Self, R>
1.0.0 · Source§fn take(self, limit: u64) -> Take<Self>where
Self: Sized,
fn take(self, limit: u64) -> Take<Self>where
Self: Sized,
limit bytes from it. Read moreSource§fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>where
Self: Sized,
fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>where
Self: Sized,
read_array)Source§impl Write for TcpSocket
impl Write for TcpSocket
Source§fn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
Source§fn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
Source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector)1.0.0 · Source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
Source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored)Source§impl<'a> Write for &'a TcpSocket
impl<'a> Write for &'a TcpSocket
Source§fn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
Source§fn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
Source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector)1.0.0 · Source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
Source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored)