Atom

TCP client and server

Save as tcp-echo.atom. The server owns its listener and accepted socket on a worker VM. A channel communicates the ephemeral port. The client reads until EOF after shutting down its write stream. This ASCII request fits one small buffer, but the round trip accumulates all bytes before decoding.

Send a request and read until EOF

The client finishes its write side to tell the server the request is complete. It keeps reading because a single read can return only part of the reply.

Excerpt
        write(client, 'Echo through TCP')
        net.shutdown(client)
        response = create(u8, 0)
        while true:
            chunk = read(client, 4096)
            if count(chunk) == 0:
                break
            for byte in chunk:
                add(response, byte)
Show full source 43 lines
tcp-echo.atom
use binary
use net
use task

func server(ports):
    listener = net.listen('127.0.0.1', 0, {timeout = 3})
    try:
        task.send(ports, net.local(listener).port)
        peer = net.accept(listener)
        try:
            while true:
                chunk = read(peer, 4096)
                if count(chunk) == 0:
                    break
                write(peer, chunk)
        finally:
            net.close(peer)
    finally:
        net.close(listener)

ports = task.channel()
worker = task.spawn(server, ports)
try:
    port = task.receive(ports, 3).value
    client = net.connect('127.0.0.1', port, {timeout = 3})
    try:
        write(client, 'Echo through TCP')
        net.shutdown(client)
        response = create(u8, 0)
        while true:
            chunk = read(client, 4096)
            if count(chunk) == 0:
                break
            for byte in chunk:
                add(response, byte)
        assert(binary.text(response) == 'Echo through TCP')
        print(binary.text(response))
    finally:
        net.close(client)
    task.wait(worker, 3)
finally:
    task.close(ports)
    task.cancel(worker)