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.

withConnect : Str, U16, (Stream -> Task a err) -> Task a [ TcpConnectErr ConnectErr, TcpPerformErr err ]

Opens a TCP connection to a remote host and perform a Task with it.

# Connect to localhost:8080 and send "Hi from Roc!"
stream = Tcp.withConnect! "localhost" 8080
Tcp.writeUtf8 "Hi from Roc!" stream

The connection is automatically closed after the Task is completed. Examples of valid hostnames:

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

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

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

Read an exact number of bytes or fail.

File.readExactly 64 stream

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

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

Read until a delimiter or EOF is reached.

# Read until null terminator
File.readUntil 0 stream

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 , TcpUnexpectedEOF ]

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 : List U8, Stream -> Task {} [TcpWriteErr StreamErr]

Writes bytes to a TCP stream.

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

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

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

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

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

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)"