Sockets

high-level socket interface and relevant socket communication methods


Functions

Predicates


The Sockets module provides a straightforward way to handle network communication using TCP/UDP sockets. Rather than dealing with low-level details, you can focus on building networked applications with just a few simple functions.

Key Concepts

  • Server sockets listen for incoming connections
  • Client sockets connect to servers
  • Messages can be sent/received as strings
  • Both TCP (default) and UDP protocols are supported

Basic Usage

Creating a Server

server: listen 8000
print "Server listening on port 8000..."

Important
Always remember to unplug your sockets when you're done with them to free up system resources.

Accepting Connections & Handling Messages

; accept new client
client: accept server

; send a message
send client "hello!"

; receive a message
message: receive.timeout:1000 client    ; timeout after 1 second if no message

Caution
Watch out for message sizes when using receive: for large ones, consider implementing a chunking strategy or using a protocol with clear message boundaries.

Using UDP

When you need faster, connectionless communication:

server: listen.udp 8000

Warning
UDP messages may arrive out of order or not at all. Only use UDP when your application can handle message loss.

Common Patterns

Echo Server

A minimal TCP server that echoes back messages:

; server.art
server: listen 8000

print "Server listening on port 8000..."
while [true][
    client: accept server
    message: receive client
    send client ~"got: |message|"
    unplug client    ; clean up when done
]

And its corresponding client:

; client.art
client: connect.to:"localhost" 8000
send client "hello server!"
print receive client
unplug client

Multi-Client Chat Server

A more complete example showing how to handle multiple clients:

server: listen 8000
clients: []

print "Chat server started..."
while [true][
    ; accept new connection
    client: accept server
    'clients ++ client
    
    ; broadcast arrival
    loop clients 'c [
        if c <> client ->
            send c "* new user joined *"
    ]
    
    ; handle messages
    ; note: in a real implementation, you'd want to handle
    ; client disconnections and cleanup as well
    while [true][
        message: receive client
        if empty? message -> break
        
        ; broadcast to all other clients
        loop clients 'c [
            if c <> client ->
                send c message
        ]
    ]
]