mod listener
srcTCP listener: a socket bound and listening for incoming connections.
TcpListener wraps a RawSocket in the listening state. Call
accept() to receive incoming connections as TcpStream instances.
Design rules enforced here:
SO_REUSEADDRis set before everybind()call.TCP_NODELAYis set on every acceptedTcpStream.accept()setsTCP_NODELAYon the client socket automatically.
Structs
struct TcpListener
struct TcpListener
A TCP socket in the listening state.
TcpListener accepts incoming TCP connections and returns each one
as a TcpStream. SO_REUSEADDR is always set before bind().
The listener is closed automatically when the struct is destroyed.
Thread safety:
Not thread-safe in v0.1.0. Do not call accept() concurrently.
Example:
from flare.tcp import TcpListener, TcpStream
from flare.net import SocketAddr
var listener = TcpListener.bind(SocketAddr.localhost(8080))
var stream = listener.accept() # blocks until a client connects
stream.write_all("welcome".as_bytes())
Methods
fn __init__ static
__init__(out self, var socket: RawSocket, local: SocketAddr)
Wrap an already-bound, listening ``RawSocket``.
Safety:
socket must already be in the listening state (listen(2)
was called). The caller must not close socket after this.
Args
Open, listening socket (ownership transferred).
The address the socket was bound to.
Returns
fn __init__ static
__init__(out self, *, deinit take: Self)
Args
Returns
fn __del__
__del__(deinit self)
Args
fn bind static
bind(addr: SocketAddr) -> Self
Bind a TCP listener to ``addr`` with default options.
SO_REUSEADDR is set before binding. The backlog is 128.
Example:
var l = TcpListener.bind(SocketAddr.localhost(8080))
Args
The local address to bind (use port 0 for OS-assigned port).
Returns
A TcpListener ready to call accept().
β οΈ Raises
AddressInUse: If the port is already in use. NetworkError: For any other OS bind/listen error.
fn bind_with_options static
bind_with_options(addr: SocketAddr, backlog: Int = 128, reuse_port: Bool = False) -> Self
Bind with explicit backlog and ``SO_REUSEPORT`` control.
Example:
var l = TcpListener.bind_with_options(
SocketAddr.localhost(8080), backlog=1024, reuse_port=True
)
Args
The local address to bind.
Returns
A TcpListener ready to call accept().
β οΈ Raises
AddressInUse: If the port is already in use. NetworkError: For any other OS error.
fn accept
accept(self) -> TcpStream
Block until an incoming connection arrives and return it.
Sets TCP_NODELAY on the accepted socket automatically.
Example:
while True:
var client = listener.accept()
client.write_all("hello".as_bytes())
client.close()
Args
Returns
A connected TcpStream for the new client.
β οΈ Raises
NetworkError: If accept(2) fails.
fn local_addr
local_addr(self) -> SocketAddr
Return the local address the listener is bound to.
Args
Returns
The bound SocketAddr (useful when port 0 was requested).
fn close
close(mut self)
Close the listening socket. Idempotent.