Struct std::os::unix::net::UnixStream

1.10.0 · source ·
pub struct UnixStream(_);
Available on Unix only.
Expand description

Unix 流套接字。

Examples

use std::os::unix::net::UnixStream;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    let mut stream = UnixStream::connect("/path/to/my/socket")?;
    stream.write_all(b"hello world")?;
    let mut response = String::new();
    stream.read_to_string(&mut response)?;
    println!("{response}");
    Ok(())
}
Run

Implementations§

source§

impl UnixStream

source

pub fn connect<P: AsRef<Path>>(path: P) -> Result<UnixStream>

连接到以 path 命名的套接字。

Examples
use std::os::unix::net::UnixStream;

let socket = match UnixStream::connect("/tmp/sock") {
    Ok(sock) => sock,
    Err(e) => {
        println!("Couldn't connect: {e:?}");
        return
    }
};
Run
1.70.0 · source

pub fn connect_addr(socket_addr: &SocketAddr) -> Result<UnixStream>

连接到 address 指定的套接字。

Examples
use std::os::unix::net::{UnixListener, UnixStream};

fn main() -> std::io::Result<()> {
    let listener = UnixListener::bind("/path/to/the/socket")?;
    let addr = listener.local_addr()?;

    let sock = match UnixStream::connect_addr(&addr) {
        Ok(sock) => sock,
        Err(e) => {
            println!("Couldn't connect: {e:?}");
            return Err(e)
        }
    };
    Ok(())
}
Run
source

pub fn pair() -> Result<(UnixStream, UnixStream)>

创建一对未命名的已连接套接字。

返回两个相互连接的 UnixStream

Examples
use std::os::unix::net::UnixStream;

let (sock1, sock2) = match UnixStream::pair() {
    Ok((sock1, sock2)) => (sock1, sock2),
    Err(e) => {
        println!("Couldn't create a pair of sockets: {e:?}");
        return
    }
};
Run
source

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

为底层套接字创建一个新的独立的拥有所有权的句柄。

返回的 UnixStream 是与此对象引用相同的流的引用。 两个句柄将读取和写入相同的数据流,并且在一个流上设置的选项将传播到另一流。

Examples
use std::os::unix::net::UnixStream;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    let sock_copy = socket.try_clone().expect("Couldn't clone socket");
    Ok(())
}
Run
source

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

返回此连接本地一半的套接字地址。

Examples
use std::os::unix::net::UnixStream;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    let addr = socket.local_addr().expect("Couldn't get local address");
    Ok(())
}
Run
source

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

返回此连接的另一半的套接字地址。

Examples
use std::os::unix::net::UnixStream;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    let addr = socket.peer_addr().expect("Couldn't get peer address");
    Ok(())
}
Run
source

pub fn peer_cred(&self) -> Result<UCred>

🔬This is a nightly-only experimental API. (peer_credentials_unix_socket #42839)

获取此 Unix 域套接字的对等凭据。

Examples
#![feature(peer_credentials_unix_socket)]
use std::os::unix::net::UnixStream;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    let peer_cred = socket.peer_cred().expect("Couldn't get peer credentials");
    Ok(())
}
Run
source

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

设置套接字的读取超时。

如果提供的值为 None,则 read 调用将无限期阻塞。 如果将零 Duration 传递给此方法,则返回 Err

Examples
use std::os::unix::net::UnixStream;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
    Ok(())
}
Run

如果将零 Duration 传递给此方法,则返回 Err

use std::io;
use std::os::unix::net::UnixStream;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
    let err = result.unwrap_err();
    assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    Ok(())
}
Run
source

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

设置套接字的写超时。

如果提供的值为 None,则 write 调用将无限期阻塞。 如果将零 Duration 传递给此方法,则返回 Err

Examples
use std::os::unix::net::UnixStream;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    socket.set_write_timeout(Some(Duration::new(1, 0)))
        .expect("Couldn't set write timeout");
    Ok(())
}
Run

如果将零 Duration 传递给此方法,则返回 Err

use std::io;
use std::net::UdpSocket;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let socket = UdpSocket::bind("127.0.0.1:34254")?;
    let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
    let err = result.unwrap_err();
    assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    Ok(())
}
Run
source

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

返回此套接字的读取超时。

Examples
use std::os::unix::net::UnixStream;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
    assert_eq!(socket.read_timeout()?, Some(Duration::new(1, 0)));
    Ok(())
}
Run
source

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

返回此套接字的写入超时。

Examples
use std::os::unix::net::UnixStream;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    socket.set_write_timeout(Some(Duration::new(1, 0)))
        .expect("Couldn't set write timeout");
    assert_eq!(socket.write_timeout()?, Some(Duration::new(1, 0)));
    Ok(())
}
Run
source

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

将套接字移入或移出非阻塞模式。

Examples
use std::os::unix::net::UnixStream;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    socket.set_nonblocking(true).expect("Couldn't set nonblocking");
    Ok(())
}
Run
source

pub fn set_passcred(&self, passcred: bool) -> Result<()>

🔬This is a nightly-only experimental API. (unix_socket_ancillary_data #76915)

移动套接字以将 unix 凭据作为 SocketAncillary 中的控制消息传递。

设置套接字选项 SO_PASSCRED

Examples
#![feature(unix_socket_ancillary_data)]
use std::os::unix::net::UnixStream;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    socket.set_passcred (true).expect ("无法设置密码");
    Ok(())
}
Run
source

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

🔬This is a nightly-only experimental API. (unix_socket_ancillary_data #76915)

获取用于在 SocketAncillary 中传递 unix 凭据的套接字的当前值。 可以通过 set_passcred 更改此值。

获取套接字选项 SO_PASSCRED

source

pub fn set_mark(&self, mark: u32) -> Result<()>

🔬This is a nightly-only experimental API. (unix_set_mark #96467)

设置套接字的 id 以进行网络过滤

#![feature(unix_set_mark)]
use std::os::unix::net::UnixStream;

fn main() -> std::io::Result<()> {
    let sock = UnixStream::connect("/tmp/sock")?;
    sock.set_mark(32)?;
    Ok(())
}
Run
source

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

返回 SO_ERROR 选项的值。

Examples
use std::os::unix::net::UnixStream;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    if let Ok(Some(err)) = socket.take_error() {
        println!("Got error: {err:?}");
    }
    Ok(())
}
Run
特定于平台

在 Redox 上,它总是返回 None

source

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

关闭此连接的读取,写入或两半。

此函数将导致对指定部分的所有未决和 future I/O 调用立即返回适当的值 (请参见 Shutdown 的文档)。

Examples
use std::os::unix::net::UnixStream;
use std::net::Shutdown;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    socket.shutdown(Shutdown::Both).expect("shutdown function failed");
    Ok(())
}
Run
source

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

🔬This is a nightly-only experimental API. (unix_socket_peek #76923)

从套接字所连接的远程地址接收套接字上的数据,而无需从队列中删除该数据。

成功时,返回偷看的字节数。

连续调用返回相同的数据。 这是通过将 MSG_PEEK 作为标志传递给底层的 recv 系统调用来实现的。

Examples
#![feature(unix_socket_peek)]

use std::os::unix::net::UnixStream;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    let mut buf = [0; 10];
    let len = socket.peek(&mut buf).expect("peek failed");
    Ok(())
}
Run
source

pub fn recv_vectored_with_ancillary( &self, bufs: &mut [IoSliceMut<'_>], ancillary: &mut SocketAncillary<'_> ) -> Result<usize>

🔬This is a nightly-only experimental API. (unix_socket_ancillary_data #76915)

从套接字接收数据和辅助数据。

成功时,返回读取的字节数。

Examples
#![feature(unix_socket_ancillary_data)]
use std::os::unix::net::{UnixStream, SocketAncillary, AncillaryData};
use std::io::IoSliceMut;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    let mut buf1 = [1; 8];
    let mut buf2 = [2; 16];
    let mut buf3 = [3; 8];
    let mut bufs = &mut [
        IoSliceMut::new(&mut buf1),
        IoSliceMut::new(&mut buf2),
        IoSliceMut::new(&mut buf3),
    ][..];
    let mut fds = [0; 8];
    let mut ancillary_buffer = [0; 128];
    let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]);
    let size = socket.recv_vectored_with_ancillary(bufs, &mut ancillary)?;
    println!("received {size}");
    for ancillary_result in ancillary.messages() {
        if let AncillaryData::ScmRights(scm_rights) = ancillary_result.unwrap() {
            for fd in scm_rights {
                println!("receive file descriptor: {fd}");
            }
        }
    }
    Ok(())
}
Run
source

pub fn send_vectored_with_ancillary( &self, bufs: &[IoSlice<'_>], ancillary: &mut SocketAncillary<'_> ) -> Result<usize>

🔬This is a nightly-only experimental API. (unix_socket_ancillary_data #76915)

在套接字上发送数据和辅助数据。

成功时,返回写入的字节数。

Examples
#![feature(unix_socket_ancillary_data)]
use std::os::unix::net::{UnixStream, SocketAncillary};
use std::io::IoSlice;

fn main() -> std::io::Result<()> {
    let socket = UnixStream::connect("/tmp/sock")?;
    let buf1 = [1; 8];
    let buf2 = [2; 16];
    let buf3 = [3; 8];
    let bufs = &[
        IoSlice::new(&buf1),
        IoSlice::new(&buf2),
        IoSlice::new(&buf3),
    ][..];
    let fds = [0, 1, 2];
    let mut ancillary_buffer = [0; 128];
    let mut ancillary = SocketAncillary::new(&mut ancillary_buffer[..]);
    ancillary.add_fds(&fds[..]);
    socket.send_vectored_with_ancillary(bufs, &mut ancillary)
        .expect("send_vectored_with_ancillary function failed");
    Ok(())
}
Run

Trait Implementations§

1.63.0 · source§

impl AsFd for UnixStream

source§

fn as_fd(&self) -> BorrowedFd<'_>

借用文件描述符。 Read more
source§

impl AsRawFd for UnixStream

source§

fn as_raw_fd(&self) -> RawFd

提取原始文件描述符。 Read more
source§

impl Debug for UnixStream

source§

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

使用给定的格式化程序格式化该值。 Read more
1.63.0 · source§

impl From<OwnedFd> for UnixStream

source§

fn from(owned: OwnedFd) -> Self

从输入类型转换为此类型。
1.63.0 · source§

impl From<UnixStream> for OwnedFd

source§

fn from(unix_stream: UnixStream) -> OwnedFd

从输入类型转换为此类型。
source§

impl FromRawFd for UnixStream

source§

unsafe fn from_raw_fd(fd: RawFd) -> UnixStream

根据给定的原始文件描述符构造 Self 的新实例。 Read more
source§

impl IntoRawFd for UnixStream

source§

fn into_raw_fd(self) -> RawFd

消费这个对象,返回原始的底层文件描述符。 Read more
source§

impl<'a> Read for &'a UnixStream

source§

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

从该源中提取一些字节到指定的缓冲区中,返回读取的字节数。 Read more
source§

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

read 相似,不同之处在于它读入缓冲区的一部分。 Read more
source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector #69941)
确定此 Read 是否具有有效的 read_vectored 实现。 Read more
1.0.0 · source§

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

读取所有字节,直到此源中的 EOF 为止,然后将它们放入 bufRead more
1.0.0 · source§

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

读取这个源中的所有字节,直到 EOF 为止,然后将它们追加到 bufRead more
1.6.0 · source§

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

读取填充 buf 所需的确切字节数。 Read more
source§

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

🔬This is a nightly-only experimental API. (read_buf #78485)
从此源中提取一些字节到指定的缓冲区中。 Read more
source§

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

🔬This is a nightly-only experimental API. (read_buf #78485)
读取填充 cursor 所需的确切字节数。 Read more
1.0.0 · source§

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

为这个 Read 实例创建一个 “by reference” 适配器。 Read more
1.0.0 · source§

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

将此 Read 实例的字节数转换为 IteratorRead more
1.0.0 · source§

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

创建一个适配器,将这个流与另一个链接起来。 Read more
1.0.0 · source§

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

创建一个适配器,最多从中读取 limit 个字节。 Read more
source§

impl Read for UnixStream

source§

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

从该源中提取一些字节到指定的缓冲区中,返回读取的字节数。 Read more
source§

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

read 相似,不同之处在于它读入缓冲区的一部分。 Read more
source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector #69941)
确定此 Read 是否具有有效的 read_vectored 实现。 Read more
1.0.0 · source§

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

读取所有字节,直到此源中的 EOF 为止,然后将它们放入 bufRead more
1.0.0 · source§

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

读取这个源中的所有字节,直到 EOF 为止,然后将它们追加到 bufRead more
1.6.0 · source§

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

读取填充 buf 所需的确切字节数。 Read more
source§

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

🔬This is a nightly-only experimental API. (read_buf #78485)
从此源中提取一些字节到指定的缓冲区中。 Read more
source§

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

🔬This is a nightly-only experimental API. (read_buf #78485)
读取填充 cursor 所需的确切字节数。 Read more
1.0.0 · source§

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

为这个 Read 实例创建一个 “by reference” 适配器。 Read more
1.0.0 · source§

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

将此 Read 实例的字节数转换为 IteratorRead more
1.0.0 · source§

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

创建一个适配器,将这个流与另一个链接起来。 Read more
1.0.0 · source§

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

创建一个适配器,最多从中读取 limit 个字节。 Read more
source§

impl<'a> Write for &'a UnixStream

source§

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

在此 writer 中写入一个缓冲区,返回写入的字节数。 Read more
source§

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

类似于 write,不同之处在于它是从缓冲区切片中写入数据的。 Read more
source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector #69941)
确定此 Writer 是否具有有效的 write_vectored 实现。 Read more
source§

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

刷新此输出流,确保所有中间缓冲的内容均到达其目的地。 Read more
1.0.0 · source§

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

尝试将整个缓冲区写入此 writer。 Read more
source§

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

🔬This is a nightly-only experimental API. (write_all_vectored #70436)
尝试将多个缓冲区写入此 writer。 Read more
1.0.0 · source§

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

将格式化的字符串写入此 writer,返回遇到的任何错误。 Read more
1.0.0 · source§

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

为这个 Write 实例创建一个 “by reference” 适配器。 Read more
source§

impl Write for UnixStream

source§

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

在此 writer 中写入一个缓冲区,返回写入的字节数。 Read more
source§

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

类似于 write,不同之处在于它是从缓冲区切片中写入数据的。 Read more
source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector #69941)
确定此 Writer 是否具有有效的 write_vectored 实现。 Read more
source§

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

刷新此输出流,确保所有中间缓冲的内容均到达其目的地。 Read more
1.0.0 · source§

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

尝试将整个缓冲区写入此 writer。 Read more
source§

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

🔬This is a nightly-only experimental API. (write_all_vectored #70436)
尝试将多个缓冲区写入此 writer。 Read more
1.0.0 · source§

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

将格式化的字符串写入此 writer,返回遇到的任何错误。 Read more
1.0.0 · source§

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

为这个 Write 实例创建一个 “by reference” 适配器。 Read more

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

获取 selfTypeIdRead more
source§

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

source§

fn borrow(&self) -> &T

从拥有的值中一成不变地借用。 Read more
source§

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

source§

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

从拥有的值中借用。 Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

返回未更改的参数。

source§

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

source§

fn into(self) -> U

调用 U::from(self)

也就是说,这种转换是 From<T> for U 实现选择执行的任何操作。

source§

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

§

type Error = Infallible

发生转换错误时返回的类型。
source§

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

执行转换。
source§

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

§

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

发生转换错误时返回的类型。
source§

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

执行转换。