For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).
TCPStream
struct TCPStream
A TCP connection.
Create one with TCPStream(connect=), TCPSocket.connect(), or
TCPListener.accept().
Examples:
from std.net import SocketAddrV4
from std.net.tcp import TCPStream
def main() raises:
var stream = TCPStream(connect=.v4(SocketAddrV4(.localhost, 8080)))
stream.write_all("ping".as_bytes())
var buffer = List[Byte](length=1024, fill=0)
var n = stream.read(buffer)
stream^.close()
Implemented traits
Methods
__init__
def __init__(out self, *, connect: SocketAddr)
Connects to a remote address.
Args:
- connect (
SocketAddr): The remote address.
Raises:
If the connection fails, such as when nothing listens at
connect.
__deinit__
def __deinit__(deinit self)
Closes the connection, ignoring any error.
close
def close(deinit self)
Closes the connection, consuming the stream.
Raises:
If the close fails.
read
def read(self, buffer: MutSpan[UInt8]) -> Int
Reads bytes into buffer, waiting until at least one arrives.
Args:
- buffer (
MutSpan[UInt8]): Where to put the bytes.
Returns:
Int: How many bytes it read: 0 once the peer has closed its end, or if
buffer is empty.
Raises:
If the read fails, such as when the peer resets the connection.
write
def write(self, bytes: ImmSpan[UInt8]) -> Int
Writes some of bytes, waiting until at least one can be written.
To write all of them, use write_all().
Args:
- bytes (
ImmSpan[UInt8]): The bytes to write.
Returns:
Int: How many bytes it wrote, which can be fewer than len(bytes).
Raises:
If the write fails, such as when the peer has closed the connection.
write_all
def write_all(self, bytes: ImmSpan[UInt8])
Writes all of bytes by calling write() in a loop.
Args:
- bytes (
ImmSpan[UInt8]): The bytes to write.
Raises:
If a write fails, such as when the peer has closed the connection.
Some of bytes may have been written before the error.
local_addr
def local_addr(self) -> SocketAddr
Returns the local address of the connection.
Returns:
SocketAddr: The address.
Raises:
If the address can't be read.
peer_addr
def peer_addr(self) -> SocketAddr
Returns the address of the peer.
Returns:
SocketAddr: The address.
Raises:
If the address can't be read, such as when the peer has reset the connection.
set_option
def set_option[Option: SettableSocketOption](self, var option: Option.OptionType)
Sets a socket option.
Parameters:
- Option (
SettableSocketOption): The option to set, such asNoDelay.
Args:
- option (
Option.OptionType): The option's new value.
Raises:
If the option can't be set.
get_option
def get_option[Option: GettableSocketOption](self) -> Option.OptionType
Returns a socket option's value.
Parameters:
- Option (
GettableSocketOption): The option to read, such asNoDelay.
Returns:
Option.OptionType: The option's value.
Raises:
If the option can't be read.