Tcp
Stream
Represents a TCP stream.
ConnectErr
Represents errors that can occur when connecting to a remote host.
StreamErr
Represents errors that can occur when performing a Task
with a Stream
.
connect! : Str, U16 => Result Stream ConnectErr
Opens a TCP connection to a remote host.
# Connect to localhost:8080 stream = Tcp.connect! "localhost" 8080
The connection is automatically closed when the last reference to the stream is dropped. Examples of valid hostnames:
127.0.0.1
::1
localhost
roc-lang.org
read_up_to! : Stream, U64 => Result (List U8) [TcpReadErr StreamErr]
Read up to a number of bytes from the TCP stream.
# Read up to 64 bytes from the stream and convert to a Str received = File.read_up_to! stream 64 Str.fromUtf8 received
To read an exact number of bytes or fail, you can use
Tcp.read_exactly!
instead.
read_exactly! :
Stream,
U64
=> Result (List U8)
[
TcpReadErr StreamErr,
TcpUnexpectedEOF
]
Read an exact number of bytes or fail.
bytes = File.read_exactly!? stream 64
TcpUnexpectedEOF
is returned if the stream ends before the specfied number of bytes is reached.
read_until! : Stream, U8 => Result (List U8) [TcpReadErr StreamErr]
Read until a delimiter or EOF is reached.
# Read until null terminator File.read_until! stream 0
If found, the delimiter is included as the last byte.
To read until a newline is found, you can use
Tcp.read_line!
which conveniently decodes to aStr
.
read_line! :
Stream
=> Result Str
[
TcpReadErr StreamErr,
TcpReadBadUtf8
]
Read until a newline or EOF is reached.
# Read a line and then print it to `stdout` lineStr = File.read_line! stream Stdout.line lineStr
If found, the newline is included as the last character in the Str
.
write! : Stream, List U8 => Result {} [TcpWriteErr StreamErr]
Writes bytes to a TCP stream.
# Writes the bytes 1, 2, 3 Tcp.write!? stream [1, 2, 3]
To write a
Str
, you can useTcp.write_utf8!
instead.
write_utf8! : Stream, Str => Result {} [TcpWriteErr StreamErr]
Writes a Str
to a TCP stream, encoded as UTF-8.
# Write "Hi from Roc!" encoded as UTF-8 Tcp.write_utf8! stream "Hi from Roc!"
To write unformatted bytes, you can use
Tcp.write!
instead.
connect_err_to_str : ConnectErr -> Str
Convert a ConnectErr
to a Str
you can print.
when err is TcpPerfomErr (TcpConnectErr connectErr) -> Stderr.line (Tcp.connect_err_to_str connectErr)
stream_err_to_str : StreamErr -> Str
Convert a StreamErr
to a Str
you can print.
when err is TcpPerformErr (TcpReadErr err) -> errStr = Tcp.stream_err_to_str err Stderr.line "Error while reading: $(errStr)" TcpPerformErr (TcpWriteErr err) -> errStr = Tcp.stream_err_to_str err Stderr.line "Error while writing: $(errStr)"