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 -> Task 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:

readUpTo : Stream, U64 -> Task (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.readUpTo! stream 64
Str.fromUtf8 received

To read an exact number of bytes or fail, you can use Tcp.readExactly instead.

readExactly : Stream, U64 -> Task (List U8) [ TcpReadErr StreamErr, TcpUnexpectedEOF ]

Read an exact number of bytes or fail.

File.readExactly stream 64

TcpUnexpectedEOF is returned if the stream ends before the specfied number of bytes is reached.

readUntil : Stream, U8 -> Task (List U8) [TcpReadErr StreamErr]

Read until a delimiter or EOF is reached.

# Read until null terminator
File.readUntil stream 0

If found, the delimiter is included as the last byte.

To read until a newline is found, you can use Tcp.readLine which conveniently decodes to a Str.

readLine : Stream -> Task Str [ TcpReadErr StreamErr, TcpReadBadUtf8 ]

Read until a newline or EOF is reached.

# Read a line and then print it to `stdout`
lineStr = File.readLine! stream
Stdout.line lineStr

If found, the newline is included as the last character in the Str.

write : Stream, List U8 -> Task {} [TcpWriteErr StreamErr]

Writes bytes to a TCP stream.

# Writes the bytes 1, 2, 3
Tcp.writeBytes stream [1, 2, 3]

To write a Str, you can use Tcp.writeUtf8 instead.

writeUtf8 : Stream, Str -> Task {} [TcpWriteErr StreamErr]

Writes a Str to a TCP stream, encoded as UTF-8.

# Write "Hi from Roc!" encoded as UTF-8
Tcp.writeUtf8 stream "Hi from Roc!"

To write unformatted bytes, you can use Tcp.write instead.

connectErrToStr : ConnectErr -> Str

Convert a ConnectErr to a Str you can print.

when err is
    TcpPerfomErr (TcpConnectErr connectErr) ->
        Stderr.line (Tcp.connectErrToStr connectErr)

streamErrToStr : StreamErr -> Str

Convert a StreamErr to a Str you can print.

when err is
    TcpPerformErr (TcpReadErr err) ->
        errStr = Tcp.streamErrToStr err
        Stderr.line "Error while reading: $(errStr)"

    TcpPerformErr (TcpWriteErr err) ->
        errStr = Tcp.streamErrToStr err
        Stderr.line "Error while writing: $(errStr)"