IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
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​

AnyType, Deinitable, Movable

Methods​

__init__​

def __init__(out self, *, connect: SocketAddr)

Connects to a remote address.

Args:

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:

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:

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:

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:

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:

Returns:

Option.OptionType: The option's value.

Raises:

If the option can't be read.