iyi

Playground

samples/iyi/socket.iyi

Sockets: TCP client and server in one program on loopback.

samples/iyi/socket.iyi · iyi-socket.wasm · 315 KB
# Sockets: TCP client and server in one program on loopback.
#
#   ./bin/iyi run samples/iyi/socket.iyi
#
# Binds to an ephemeral port (port 0), connects, exchanges a message each way,
# prints what arrived, and closes cleanly.

module samples/socket

import std/socket::{IyiSocket}

# Server listens on an ephemeral port. The number the kernel picks is different
# on every run, so it is used rather than printed: `bench/arena_exercise.sh`
# runs every sample twice and asks for identical output, and a sample that
# prints its port is a sample that can never answer that.
server = IyiSocket.listen(0)
port = server.local_port
puts "server listening on an ephemeral port"

# Client connects to server on loopback
client = IyiSocket.connect("127.0.0.1", port).or_panic
client.write("hello from client\n")

# Server accepts and reads the message
conn = server.accept.or_panic
msg = conn.read(1024).or_panic
puts "server received: #{msg}"

# Server replies to client
conn.write("hello from server\n")
reply = client.read(1024).or_panic
puts "client received: #{reply}"

# Clean teardown
client.close
conn.close
server.close
puts "closed"
output
Press Run.

recorded with iyi 0.18.0 (built on Crystal 1.22.0-dev [2a9653052] (2026-10-18)) · Linux 7.0.0-38-generic x86_64, QEMU Virtual CPU version 2.5+ · 2026-10-19

You can type in the pane: nothing here compiles, so what you type cannot run, and the page says which bytes it is running the moment the text stops being the recorded file. There is no standard input, no filesystem and no threads on this target, and one sample fails on purpose for exactly that reason.

Run executes iyi-socket.wasm, the module the compiler built from this file, in your browser. How this works

Try it on your machine

Copy the program into socket.iyi, change something, and run it. Only a compiler on your own machine can run what you wrote.

sh, after installing
$ iyi run socket.iyi