本文簡要介紹rust語言中 std::net::TcpListener.set_nonblocking
的用法。
用法
pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>
將此 TCP 流移入或移出非阻塞模式。
這將導致 accept
操作變為非阻塞,即立即從他們的調用中返回。如果 IO 操作成功,則返回Ok
,無需進一步操作。如果 IO 操作無法完成並需要重試,則返回類型為 io::ErrorKind::WouldBlock
的錯誤。
在 Unix 平台上,調用此方法對應於調用 fcntl
FIONBIO
。在 Windows 上調用此方法對應於調用 ioctlsocket
FIONBIO
。
例子
將 TCP 偵聽器綁定到地址,偵聽連接,並以非阻塞模式讀取字節:
use std::io;
use std::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
listener.set_nonblocking(true).expect("Cannot set non-blocking");
for stream in listener.incoming() {
match stream {
Ok(s) => {
// do something with the TcpStream
handle_connection(s);
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
// wait until network socket is ready, typically implemented
// via platform-specific APIs such as epoll or IOCP
wait_for_fd();
continue;
}
Err(e) => panic!("encountered IO error: {}", e),
}
}
相關用法
- Rust TcpListener.set_ttl用法及代碼示例
- Rust TcpListener.take_error用法及代碼示例
- Rust TcpListener.into_incoming用法及代碼示例
- Rust TcpListener.accept用法及代碼示例
- Rust TcpListener.local_addr用法及代碼示例
- Rust TcpListener.ttl用法及代碼示例
- Rust TcpListener.incoming用法及代碼示例
- Rust TcpListener.bind用法及代碼示例
- Rust TcpListener.try_clone用法及代碼示例
- Rust TcpListener用法及代碼示例
- Rust TcpStream.local_addr用法及代碼示例
- Rust TcpStream.peer_addr用法及代碼示例
- Rust TcpStream.set_nodelay用法及代碼示例
- Rust TcpStream.nodelay用法及代碼示例
- Rust TcpStream.take_error用法及代碼示例
- Rust TcpStream.write_timeout用法及代碼示例
- Rust TcpStream.peek用法及代碼示例
- Rust TcpStream.set_write_timeout用法及代碼示例
- Rust TcpStream.set_nonblocking用法及代碼示例
- Rust TcpStream.set_linger用法及代碼示例
- Rust TcpStream用法及代碼示例
- Rust TcpStream.linger用法及代碼示例
- Rust TcpStream.connect用法及代碼示例
- Rust TcpStream.ttl用法及代碼示例
- Rust TcpStream.shutdown用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 std::net::TcpListener.set_nonblocking。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。