Movatterモバイル変換


[0]ホーム

URL:


TcpListener

std::net

StructTcpListener 

1.0.0 ·Source
pub struct TcpListener(/* private fields */);
Expand description

A TCP socket server, listening for connections.

After creating aTcpListener bybinding it to a socket address, it listensfor incoming TCP connections. These can be accepted by callingaccept or byiterating over theIncoming iterator returned byincoming.

The socket will be closed when the value is dropped.

The Transmission Control Protocol is specified inIETF RFC 793.

§Examples

usestd::net::{TcpListener, TcpStream};fnhandle_client(stream: TcpStream) {// ...}fnmain() -> std::io::Result<()> {letlistener = TcpListener::bind("127.0.0.1:80")?;// accept connections and process them seriallyforstreaminlistener.incoming() {        handle_client(stream?);    }Ok(())}

Implementations§

Source§

implTcpListener

1.0.0 ·Source

pub fnbind<A:ToSocketAddrs>(addr: A) ->Result<TcpListener>

Creates a newTcpListener which will be bound to the specifiedaddress.

The returned listener is ready for accepting connections.

Binding with a port number of 0 will request that the OS assigns a portto this listener. The port allocated can be queried via theTcpListener::local_addr method.

The address type can be any implementor ofToSocketAddrs trait. Seeits documentation for concrete examples.

Ifaddr yields multiple addresses,bind will be attempted witheach of the addresses until one succeeds and returns the listener. Ifnone of the addresses succeed in creating a listener, the error returnedfrom the last attempt (the last address) is returned.

§Examples

Creates a TCP listener bound to127.0.0.1:80:

usestd::net::TcpListener;letlistener = TcpListener::bind("127.0.0.1:80").unwrap();

Creates a TCP listener bound to127.0.0.1:80. If that fails, create aTCP listener bound to127.0.0.1:443:

usestd::net::{SocketAddr, TcpListener};letaddrs = [    SocketAddr::from(([127,0,0,1],80)),    SocketAddr::from(([127,0,0,1],443)),];letlistener = TcpListener::bind(&addrs[..]).unwrap();

Creates a TCP listener bound to a port assigned by the operating systemat127.0.0.1.

usestd::net::TcpListener;letsocket = TcpListener::bind("127.0.0.1:0").unwrap();
1.0.0 ·Source

pub fnlocal_addr(&self) ->Result<SocketAddr>

Returns the local socket address of this listener.

§Examples
usestd::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};letlistener = TcpListener::bind("127.0.0.1:8080").unwrap();assert_eq!(listener.local_addr().unwrap(),           SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127,0,0,1),8080)));
1.0.0 ·Source

pub fntry_clone(&self) ->Result<TcpListener>

Creates a new independently owned handle to the underlying socket.

The returnedTcpListener is a reference to the same socket that thisobject references. Both handles can be used to accept incomingconnections and options set on one listener will affect the other.

§Examples
usestd::net::TcpListener;letlistener = TcpListener::bind("127.0.0.1:8080").unwrap();letlistener_clone = listener.try_clone().unwrap();
1.0.0 ·Source

pub fnaccept(&self) ->Result<(TcpStream,SocketAddr)>

Accept a new incoming connection from this listener.

This function will block the calling thread until a new TCP connectionis established. When established, the correspondingTcpStream and theremote peer’s address will be returned.

§Examples
usestd::net::TcpListener;letlistener = TcpListener::bind("127.0.0.1:8080").unwrap();matchlistener.accept() {Ok((_socket, addr)) =>println!("new client: {addr:?}"),Err(e) =>println!("couldn't get client: {e:?}"),}
1.0.0 ·Source

pub fnincoming(&self) ->Incoming<'_>

Returns an iterator over the connections being received on thislistener.

The returned iterator will never returnNone and will also not yieldthe peer’sSocketAddr structure. Iterating over it is equivalent tocallingTcpListener::accept in a loop.

§Examples
usestd::net::{TcpListener, TcpStream};fnhandle_connection(stream: TcpStream) {//...}fnmain() -> std::io::Result<()> {letlistener = TcpListener::bind("127.0.0.1:80")?;forstreaminlistener.incoming() {matchstream {Ok(stream) => {                handle_connection(stream);            }Err(e) => {/* connection failed */}        }    }Ok(())}
Source

pub fninto_incoming(self) ->IntoIncoming

🔬This is a nightly-only experimental API. (tcplistener_into_incoming #88373)

Turn this into an iterator over the connections being received on thislistener.

The returned iterator will never returnNone and will also not yieldthe peer’sSocketAddr structure. Iterating over it is equivalent tocallingTcpListener::accept in a loop.

§Examples
#![feature(tcplistener_into_incoming)]usestd::net::{TcpListener, TcpStream};fnlisten_on(port: u16) ->implIterator<Item = TcpStream> {letlistener = TcpListener::bind(("127.0.0.1", port)).unwrap();    listener.into_incoming()        .filter_map(Result::ok)/* Ignore failed connections */}fnmain() -> std::io::Result<()> {forstreaminlisten_on(80) {/* handle the connection here */}Ok(())}
1.9.0 ·Source

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

Sets the value for theIP_TTL option on this socket.

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

§Examples
usestd::net::TcpListener;letlistener = TcpListener::bind("127.0.0.1:80").unwrap();listener.set_ttl(100).expect("could not set TTL");
1.9.0 ·Source

pub fnttl(&self) ->Result<u32>

Gets the value of theIP_TTL option for this socket.

For more information about this option, seeTcpListener::set_ttl.

§Examples
usestd::net::TcpListener;letlistener = TcpListener::bind("127.0.0.1:80").unwrap();listener.set_ttl(100).expect("could not set TTL");assert_eq!(listener.ttl().unwrap_or(0),100);
1.9.0 ·Source

pub fnset_only_v6(&self, only_v6:bool) ->Result<()>

👎Deprecated since 1.16.0: this option can only be set before the socket is bound
1.9.0 ·Source

pub fnonly_v6(&self) ->Result<bool>

👎Deprecated since 1.16.0: this option can only be set before the socket is bound
1.9.0 ·Source

pub fntake_error(&self) ->Result<Option<Error>>

Gets the value of theSO_ERROR option on this socket.

This will retrieve the stored error in the underlying socket, clearingthe field in the process. This can be useful for checking errors betweencalls.

§Examples
usestd::net::TcpListener;letlistener = TcpListener::bind("127.0.0.1:80").unwrap();listener.take_error().expect("No error was expected");
1.9.0 ·Source

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

Moves this TCP stream into or out of nonblocking mode.

This will result in theaccept operation becoming nonblocking,i.e., immediately returning from their calls. If the IO operation issuccessful,Ok is returned and no further action is required. If theIO operation could not be completed and needs to be retried, an errorwith kindio::ErrorKind::WouldBlock is returned.

On Unix platforms, calling this method corresponds to callingfcntlFIONBIO. On Windows calling this method corresponds to callingioctlsocketFIONBIO.

§Examples

Bind a TCP listener to an address, listen for connections, and readbytes in nonblocking mode:

usestd::io;usestd::net::TcpListener;letlistener = TcpListener::bind("127.0.0.1:7878").unwrap();listener.set_nonblocking(true).expect("Cannot set non-blocking");forstreaminlistener.incoming() {matchstream {Ok(s) => {// do something with the TcpStreamhandle_connection(s);        }Err(refe)ife.kind() == io::ErrorKind::WouldBlock => {// wait until network socket is ready, typically implemented            // via platform-specific APIs such as epoll or IOCPwait_for_fd();continue;        }Err(e) =>panic!("encountered IO error: {e}"),    }}

Trait Implementations§

1.63.0 ·Source§

implAsFd forTcpListener

Available on(Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.
Source§

fnas_fd(&self) ->BorrowedFd<'_>

Borrows the file descriptor.Read more
1.0.0 ·Source§

implAsRawFd forTcpListener

Available onnon-target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.
Source§

fnas_raw_fd(&self) ->RawFd

Extracts the raw file descriptor.Read more
1.0.0 ·Source§

implAsRawSocket forTcpListener

Available onWindows only.
Source§

fnas_raw_socket(&self) ->RawSocket

Extracts the raw socket.Read more
1.63.0 ·Source§

implAsSocket forTcpListener

Available onWindows only.
Source§

fnas_socket(&self) ->BorrowedSocket<'_>

Borrows the socket.
1.0.0 ·Source§

implDebug forTcpListener

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result

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

implFrom<OwnedFd> forTcpListener

Available on(Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.
Source§

fnfrom(owned_fd:OwnedFd) -> Self

Converts to this type from the input type.
1.63.0 ·Source§

implFrom<OwnedSocket> forTcpListener

Available onWindows only.
Source§

fnfrom(owned:OwnedSocket) -> Self

Converts to this type from the input type.
1.63.0 ·Source§

implFrom<TcpListener> forOwnedFd

Available on(Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.
Source§

fnfrom(tcp_listener:TcpListener) ->OwnedFd

Takes ownership of aTcpListener’s socket file descriptor.

1.63.0 ·Source§

implFrom<TcpListener> forOwnedSocket

Available onWindows only.
Source§

fnfrom(tcp_listener:TcpListener) ->OwnedSocket

Takes ownership of aTcpListener’s socket.

1.1.0 ·Source§

implFromRawFd forTcpListener

Available onnon-target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.
Source§

unsafe fnfrom_raw_fd(fd:RawFd) ->TcpListener

Constructs a new instance ofSelf from the given raw filedescriptor.Read more
1.1.0 ·Source§

implFromRawSocket forTcpListener

Available onWindows only.
Source§

unsafe fnfrom_raw_socket(sock:RawSocket) ->TcpListener

Constructs a new I/O object from the specified raw socket.Read more
1.4.0 ·Source§

implIntoRawFd forTcpListener

Available onnon-target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.
Source§

fninto_raw_fd(self) ->RawFd

Consumes this object, returning the raw underlying file descriptor.Read more
1.4.0 ·Source§

implIntoRawSocket forTcpListener

Available onWindows only.
Source§

fninto_raw_socket(self) ->RawSocket

Consumes this object, returning the raw underlying socket.Read more

Auto Trait Implementations§

§

implFreeze forTcpListener

§

implRefUnwindSafe forTcpListener

§

implSend forTcpListener

§

implSync forTcpListener

§

implUnpin forTcpListener

§

implUnwindSafe forTcpListener

Blanket Implementations§

Source§

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

Source§

fntype_id(&self) ->TypeId

Gets theTypeId ofself.Read more
Source§

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

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
Source§

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

Source§

fnborrow_mut(&mut self) ->&mut T

Mutably borrows from an owned value.Read more
Source§

impl<T>From<T> for T

Source§

fnfrom(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fninto(self) -> U

CallsU::from(self).

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

Source§

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

Source§

typeError =Infallible

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

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>

Performs the conversion.
Source§

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

Source§

typeError = <U asTryFrom<T>>::Error

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

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>

Performs the conversion.

[8]ページ先頭

©2009-2026 Movatter.jp