Chapter 16
In This Chapter
fetchftpfetchtcpclienttcpserver and handler proceduressocket command for low-level TCP and UDP workcshw is one of the few shells with a first-class networking story. Most shells expect you to shell out to curl, wget, or netcat whenever you want to talk to the network. cshw has all of that built in, with cshw-native commands that integrate cleanly with everything else you've learned — pipes, redirection, coroutines, scripts.
The networking commands divide neatly into three tiers:
fetch (HTTP/HTTPS) and ftpfetch (FTP).tcpclient and tcpserver with handler procedures.socket command family.We'll cover all three tiers, then look at what happens when you combine networking with the coroutines from Chapter 14. That combination is where cshw really earns its keep — a parallel API scraper fits in 20 lines and runs faster than the equivalent in most "real" languages.
fetch — Downloading and API Calls Over HTTPfetch is the workhorse HTTP client. If you've used curl or wget, the shape is familiar.
fetch https://example.com
Hits the URL, prints the response body to stdout. Same as curl https://example.com — body to terminal, you decide what to do with it.
To save to a file instead, use -o (or the cshw-native /o:FILE):
fetch -o page.html https://example.com
fetch /o:page.html https://example.com # same thing
Both forms are accepted everywhere in cshw — pick whichever style fits your fingers. The Unix-style flags are the more transferable; the cshw-native /x: form is closer to the rest of Windows tooling. The book uses Unix style for portability.
To see just the response headers (HTTP HEAD-style), use -I (uppercase i, mnemonic for "info"):
fetch -I https://example.com
To see headers and body together, -v (verbose):
fetch -v https://example.com
For a non-GET method, pass -X METHOD:
fetch -X POST -d "name=alice&age=30" https://api.example.com/users
fetch -X DELETE https://api.example.com/users/42
fetch -X PUT -d "$json_body" https://api.example.com/users/42
-d "data" puts a request body in. Combined with -X POST, this is the "submit a form / call an API" pattern.
By default fetch uses WinHTTP, which negotiates HTTP/2 or HTTP/1.1 with the server. That's fine most of the time — but WinHTTP's client-side HTTP/2 is not always selected, even against a server that clearly offers it, and it has no reliable client HTTP/3 at all. When you need a specific protocol — testing an h2/h3 server, benchmarking, or just proving the wire protocol — pin it with --http2 or --http3:
fetch --http2 -I https://www.google.com/ # guaranteed HTTP/2
fetch --http3 -I https://cloudflare.com/ # guaranteed HTTP/3 (QUIC)
These don't ask WinHTTP to try — they use cshw's own native client, which guarantees the protocol: nghttp2 over SChannel TLS (ALPN h2) for HTTP/2, and msquic + nghttp3 (QUIC over UDP, ALPN h3) for HTTP/3. If the server won't speak the requested protocol, the request fails rather than silently downgrading — which is exactly what you want when the whole point is to exercise that protocol. Both are https-only, and both honour -d/-X (request bodies), -o/-O (save to file), -c (resume), and --no-check-certificate. $result is set to HTTP/2 or HTTP/3 accordingly.
These are the very same libraries that power cshw's http.dll and quicsrv servers (Chapter 19), so the client and server sides of a modern-HTTP conversation are both cshw. --http2 / --http3 need nghttp2.dll / nghttp3.dll / msquic.dll next to cshw.exe; if they're missing, only those two flags are affected — the default fetch path keeps working.
TRY IT
fetch --http3 -I https://cloudflare.com. The header block is prefixed [cshw fetch: HTTP/3] and $result is HTTP/3 — a real QUIC handshake, from a shell. Now try fetch --http2 -I https://www.google.com; same idea, over TCP + TLS.
For scripts:
fetch -q https://example.com # quiet -- no progress output
fetch -q https://api.example.com/data.json | grep "status"
Pipelines work exactly as you'd hope — fetch writes the response body to stdout, and | does the rest.
# Fetch some JSON, extract a field, do something with it
fetch -q https://api.example.com/weather/Atlanta | grep "\"temp\""
For one-off API calls, fetch plus grep/cut/sed is often enough. For repeated work or anything with real parsing needs, you might want a procedure with structured handling — or one of the heavyweight options (jq via genai, or the Chapter 11 hash-based config parsing patterns applied to the response).
fetch sets $? to non-zero on network errors or HTTP failures (4xx, 5xx):
fetch -q -o data.json https://api.example.com/data
if ($? != 0) then
echo "Fetch failed; using cached data"
cp data.json.cache data.json
endif
The exit status distinguishes a few failure modes:
| Status | Meaning |
|---|---|
| 0 | Success |
| 1 | Network error (DNS, connection, etc.) |
| 2 | HTTP error (4xx, 5xx) |
| 3 | Invalid URL |
| 4 | Local file write error |
TIP
For HTTPS endpoints with self-signed certificates (development servers, internal services with private CAs), pass --no-check-certificate to skip TLS verification. Don't use it on real services; the certificate is the only thing standing between you and a man-in-the-middle attacker. For production scripts, use the system trust store and proper certificates.
TRY IT
fetch -I https://www.anthropic.com. You should see the response headers, a line reporting the protocol used (HTTP/1.1 or HTTP/2), and a 200 status; fetch also leaves the negotiated protocol in $result. Now try fetch -I https://does-not-exist-12345.com. The exit code will be non-zero and you'll see the DNS error.
ftpfetch — FTP TransfersFor FTP servers — increasingly rare but still in use for some scientific data, software mirrors, and legacy systems — cshw has ftpfetch. The shape is similar to fetch:
ftpfetch ftp://ftp.example.com/pub/file.zip
ftpfetch -o local.zip ftp://ftp.example.com/file.zip
ftpfetch -u myuser -p mypass ftp://ftp.example.com/private/data.txt
ftpfetch ftp://user:pass@ftp.example.com/file.txt
Anonymous FTP works by default (no credentials needed); authenticated transfers take -u/-p flags or credentials embedded in the URL.
By default, ftpfetch uses passive mode (works through most firewalls). Pass --active if the server requires active mode — generally only on legacy networks.
WARNING
FTP transmits credentials in plain text. Don't use it for anything sensitive. For secure transfers, prefer HTTPS via fetch, or use an SFTP client (outside the shell). The protocol is widely supported, but its security model is essentially "everyone on the wire can read everything."
tcpclient — One-Shot TCP Request/ResponseWhen you want to talk to a TCP service that isn't HTTP/FTP — a database health check, a custom protocol, a quick line-based service — tcpclient is the right tool. It connects, optionally sends, optionally receives, and closes.
tcpclient localhost 8080 # just connect (test if listening)
tcpclient localhost 8080 /send:"PING" /recv # send PING, get response
tcpclient example.com 80 /send:"GET / HTTP/1.0\r\nHost: example.com\r\n\r\n" /recv
The exit code tells you whether the connection succeeded. The /recv flag captures the response in $result.
Connection probing — is a server up?
tcpclient localhost 8080
if ($? == 0) then
echo "Service is up."
else
echo "Service is down."
endif
That's the cshw equivalent of nc -z localhost 8080. Three lines and zero external dependencies.
Custom protocol speakers — send a command, read a response.
proc redis_ping
tcpclient localhost 6379 /send:"PING\r\n" /recv
if ("$result" =~ "PONG") then
return 0
else
return 1
endif
endproc
Half of "talking to network services" is a send/recv pair. tcpclient reduces that to one command.
tcpclient defaults to a 5-second timeout for both connection and receive. Override with /timeout:ms:
tcpclient slow-server.example.com 8080 /timeout:30000 /recv
Useful for health checks where you specifically want a short timeout — "if it doesn't answer in 2 seconds, it's down."
tcpclient slow-server.example.com 8080 /timeout:2000
if ($? != 0) then
echo "Server unresponsive."
endif
TECHNICAL STUFF
tcpclient does not support TLS. For HTTPS, use fetch. For other TLS-encrypted protocols (SMTPS, IMAPS, secure WebSocket, etc.), you'd need an external client (openssl s_client, a real programming language). The low-level socket command is also plain TCP only; cshw's networking commands focus on the unencrypted protocols and HTTP-with-TLS-handled-by-the-system-stack.
tcpserver — A Server in Three LinesThis is one of cshw's most distinctive features. Most shells make writing a server actively painful — you fight with socat or write a wrapper around nc -l. cshw lets you define a server in the cshw scripting language itself.
The pattern: write a handler procedure that does the work for one connection, then point tcpserver at it.
proc echo_handler(sock)
socket recv $sock
socket send $sock "$result"
socket close $sock
endproc
tcpserver 8080 echo_handler
That's a full echo server. It binds port 8080, accepts incoming connections, and for each one calls echo_handler with the client socket as the argument. The handler reads what the client sent, sends it right back, and closes the connection.
You can test it from another shell:
tcpclient 127.0.0.1 8080 /send:"hello echo server" /recv
echo "$result" # "hello echo server"
Note 127.0.0.1 rather than localhost. On a current Windows box localhost resolves to the IPv6 address ::1 first, and tcpserver binds IPv4 unless you tell it otherwise — so the friendlier-looking spelling connects to nothing and sits there until it times out. Either name the v4 address explicitly, as above, or start the server dual-stack so both families reach it:
tcpserver --dual 8080 echo_handler
With --dual the server binds 0.0.0.0 and [::], and tcpclient localhost 8080 works as you would expect.
The handler can be as simple or complex as you need:
proc time_handler(sock)
set now = $(say datetime /fmt:"%Y-%m-%d %H:%M:%S")
socket send $sock "$now\n"
socket close $sock
endproc
tcpserver 1313 time_handler
A "current time" service. Clients connect, get the timestamp, the connection closes.
By default, tcpserver runs forever. Three switches limit the lifetime:
tcpserver 8080 my_handler /once # accept exactly one connection, then exit
tcpserver 8080 my_handler /max:10 # accept 10 connections, then exit
tcpserver 8080 my_handler /timeout:60000 # exit after 60s with no new connection
/once is most useful for testing — run the server in one shell, fire one client at it from another, watch the exchange. The server exits cleanly without having to Ctrl+C anything.
Combine tcpserver with corunproc and you can run the server as a coroutine, leaving your prompt usable:
corunproc tcpserver 8080 echo_handler
# Server now runs in background
# Send it some test traffic
tcpclient localhost 8080 /send:"first" /recv
echo "$result"
tcpclient localhost 8080 /send:"second" /recv
echo "$result"
# When you're done
cocancel $coid # stop the server
Real concurrent network code, written in a shell. We'll see more of this combination shortly.
The tcpserver example wouldn't be complete without an HTTP server. Here's a one-procedure HTTP server that responds to every request with a fixed page:
proc http_handler(sock)
# Read the request (we ignore it; just respond to anything)
socket recv $sock
set body = "<html><body><h1>Hello from cshw!</h1></body></html>"
set len = $#body # length of body
socket send $sock "HTTP/1.1 200 OK\r\nContent-Length: $len\r\nContent-Type: text/html\r\n\r\n$body"
socket close $sock
endproc
tcpserver 8080 http_handler
Open http://localhost:8080 in a browser and you'll see "Hello from cshw!" rendered as HTML. A working HTTP server in 12 lines of cshw.
You can make it richer — parse the request line to route by URL, look up files on disk, do API processing — but the bones of a real web server fit in those 12 lines.
TIP
tcpserver handles one connection at a time in its default form. The handler procedure runs to completion before the next connection is accepted. For genuinely concurrent serving (multiple clients in flight at once), launch the server in a coroutine and have the handler dispatch each client to its own coroutine. We'll see the pattern shortly in the worked example.
socket Command — Full Manual Controlfetch/tcpclient/tcpserver are the high-level views. For the times when you need full control — custom protocols, UDP, async I/O, anything that doesn't fit the request/response shape — there's the socket command. It's a thin wrapper over the Windows Sockets API.
socket create [-4|-6] [--dual] tcp|udp [name] # create socket, $result = id
socket bind <sock> [addr] <port> # bind to address/port
socket listen <sock> [backlog] # start listening
socket accept <sock> [/timeout:ms] [name] # accept connection, $result = client id
socket connect <sock> <host> <port> # outbound connection
socket send <sock> <data> # write
socket recv <sock> [maxbytes] [/timeout:ms] # read; $result = data
socket close <sock> | /all # close one or all
socket list # show all open sockets
socket info <sock> # detailed info on one
socket select <sock> r|w|e [/timeout:ms] # poll for I/O readiness
The same echo server, written with socket primitives instead of tcpserver:
socket create tcp server
socket bind server 8080
socket listen server
while (1) then
socket accept server
set client = $result
socket recv $client
socket send $client "$result"
socket close $client
end
That's exactly what tcpserver does under the hood. The advantage of writing it this way is control — you can put logic between accept and recv (logging, IP filtering, throttling, etc.), use timeouts, or set socket options that the higher-level command doesn't expose.
socket create tcp client
socket connect client api.example.com 80
socket send client "GET / HTTP/1.0\r\nHost: api.example.com\r\n\r\n"
socket recv client 8192
echo "$result"
socket close client
Same effect as tcpclient, written longhand. Reach for this when you need to do several sends and receives over the same connection (the high-level tcpclient is one-shot).
UDP works the same as TCP, just with udp instead of tcp in create:
socket create udp sender
socket connect sender 192.168.1.100 5000 # sets the default peer
socket send sender "ping packet"
socket close sender
UDP is the right answer for fire-and-forget telemetry, simple state-broadcast protocols, and any case where you'd rather drop a packet than wait for retransmission. Examples: SNMP, syslog, time servers, game-server discovery.
socket select — readiness pollingFor servers that handle multiple clients without spawning coroutines (or for clients waiting on slow responses), socket select lets you ask "is this socket ready to read/write?" without blocking:
socket select my_sock r /timeout:1000
if ("$result" == "r") then
socket recv my_sock
# ... process data ...
else
echo "Nothing to read in 1 second."
endif
The flags: r (readable), w (writable), e (error). Combine for "any of these" by passing rw or rwe.
TECHNICAL STUFF
Socket IDs in cshw are names, not OS file descriptors. The first argument to create is the name you'll use to refer to it (server, my_sock, etc.). If you don't pass a name, cshw assigns one like sock1, sock2 and returns it in $result. Names are convenient for scripts because they don't change across runs and they're easy to refer to.
This is the chapter's centerpiece. cshw networking commands plus coroutines give you genuine concurrent network programming.
fetch — N URLs at onceThe simplest possible pattern. Suppose you have a list of URLs to download:
foreach url ($urls)
fetch -q -o "$(basename $url)" $url
end
That's serial. If each fetch takes 2 seconds and there are 50 URLs, you're waiting 100 seconds. The coroutine version:
proc fetch_one
fetch -q -o "$(basename $1)" $1
endproc
foreach url ($urls)
corunproc fetch_one $url
end
cowait /all
Same job, but all 50 fetches run concurrently — total time is ~2 seconds plus a bit, whatever the slowest one takes. The bandwidth and concurrency limits of your network become the bottleneck, not the script.
fetch — N at a timeIf you don't want to launch 50 simultaneous downloads (politeness, server limits, your own bandwidth), use a semaphore (Chapter 15):
semcreate fetch_pool 8 8 # max 8 concurrent fetches
proc bounded_fetch
semaphore fetch_pool acquire
fetch -q -o "$(basename $1)" $1
semaphore fetch_pool release
endproc
foreach url ($urls)
corunproc bounded_fetch $url
end
cowait /all
sync destroy semaphore fetch_pool
50 coroutines launch, but only 8 are actually fetching at any moment. The rest block at acquire until a slot opens. Total time becomes "(N / 8) × per-fetch-time" — a sweet spot between fully serial and fully concurrent.
For a server that serves many clients in parallel, dispatch each accepted connection to its own coroutine:
proc handle_client
set sock = $1
socket recv $sock
set message = $result
echo "[client $sock] received: $message"
socket send $sock "Got your message: $message\n"
socket close $sock
endproc
proc dispatcher(sock)
corunproc handle_client $sock
endproc
tcpserver 8080 dispatcher
Notice the indirection: tcpserver calls dispatcher (synchronously, one accept at a time, fast), and dispatcher immediately fires off a coroutine to actually handle the connection. The accept loop is free to take the next connection while the previous one is still being processed.
This is the standard "fork-per-connection" pattern, but using coroutines instead of forks — much lighter weight, much better suited to the shell.
Let's tie it all together. Suppose you have a list of usernames and you want to fetch each one's profile from a JSON API, in parallel, with bounded concurrency, and collect the results.
# api_scrape.cshw — parallel API fetcher
#
# Reads usernames.txt (one per line), fetches each user's profile
# from a JSON API, and writes results to profiles.json.
set base_url = "https://api.example.com/users"
set output = "profiles.json"
set max_concurrent = 5
semcreate api_pool $max_concurrent $max_concurrent
coset success_count 0
coset failure_count 0
# Initialize output file (just an opening bracket)
echo "[" > $output
proc fetch_profile
set username = $1
semaphore api_pool acquire
fetch -q -o "_tmp_$username.json" "$base_url/$username"
set fetch_status = $?
semaphore api_pool release
if ($fetch_status == 0) then
# Append to output (mutex to avoid interleaved writes)
mutex output_lock lock
echo "," >> $output # delimiter (extra comma stripped at end)
type "_tmp_$username.json" >> $output
mutex output_lock unlock
rm "_tmp_$username.json"
coincr success_count
else
coincr failure_count
echo "[FAIL] $username -- status $fetch_status"
endif
endproc
# Launch a coroutine for each username
foreach user (`type usernames.txt`)
corunproc fetch_profile $user
end
cowait /all
# Close output file
echo "]" >> $output
# Report
coget success_count
echo ""
echo "Done. $result successes, $(coget failure_count && echo $result) failures."
sync destroyall
What this exercise:
cowait /all at the end to wait for everything before closing the outputRun it on usernames.txt with 200 names; you'll see 5 fetches happening concurrently at any moment, total wall time around (200 / 5) × per-fetch time. The output is a single JSON array of profile records.
This pattern — parallel I/O with bounded concurrency, atomic accounting, file-output mutex — is one of the most reusable in shell scripting. Once you have it in your toolkit, half of "I have a list of things, do something networky to each" problems become 30-line scripts.
The other direction. A server that handles multiple clients concurrently, each in their own coroutine.
# echo_server.cshw — concurrent echo server
coset client_counter 0
proc handle_client
set sock = $1
coincr client_counter
set client_num = $result # the slot number we got
echo "[$client_num] connected: $sock"
# Loop: read, echo back, until client disconnects
while (1) then
socket recv $sock 4096
if ($? != 0) then
break # client closed
endif
set msg = $result
if ("$msg" == "") then
break # empty read = end of stream
endif
echo "[$client_num] received: $msg"
socket send $sock "$msg"
end
socket close $sock
echo "[$client_num] disconnected"
endproc
proc dispatcher(sock)
corunproc handle_client $sock
endproc
# Run server (in background, so we can shut down with Ctrl+C cleanly)
echo "Echo server starting on port 8080. Ctrl+C to stop."
tcpserver 8080 dispatcher
Behavior:
handle_client coroutineTest it from a few different shells with tcpclient, all at once:
# Shell A
tcpclient localhost 8080 /send:"hello from A" /recv
# Shell B
tcpclient localhost 8080 /send:"hello from B" /recv
# Shell C (longer interaction with raw socket)
socket create tcp myconn
socket connect myconn localhost 8080
socket send myconn "first message"
socket recv myconn
echo $result
socket send myconn "second message"
socket recv myconn
echo $result
socket close myconn
On the server window, you'll see interleaved log lines from the concurrent clients — each carrying its slot number, so you can see which message belongs to which client.
That's a real concurrent server in 35 lines, with no Python, no Node, no compiled code. Just cshw.
Both tcpclient/tcpserver and the socket command have explicit IPv6 support:
# Force IPv6
socket create -6 tcp v6_server
socket bind v6_server "::" 8080 # IPv6 wildcard
socket listen v6_server
# IPv6 client (note the quoted literal)
tcpclient "::1" 8080
# Dual-stack server — accept both v4 and v6 clients on one socket
tcpserver --dual 8080 my_handler
The defaults:
socket create tcp NAME — IPv4tcpserver PORT HANDLER — IPv4tcpclient HOST PORT — auto-detect from the host (DNS or address literal)For most scripts, the default is fine. Pass -6 when you specifically want IPv6, or --dual for a server that needs to accept both families on one socket.
TECHNICAL STUFF
When a dual-stack server accepts an IPv4 client, the peer address would normally show up in socket info as the IPv4-mapped IPv6 form ::ffff:192.0.2.1. By default, cshw strips this to plain 192.0.2.1 for readability. Pass --keep-mapped to keep the on-the-wire IPv6 form, useful when your logging tools assume one format consistently.
What's not in the cshw networking commands:
fetch. Raw socket, tcpclient, and tcpserver are all plain TCP. For HTTPS, use fetch. For other TLS-protected protocols (SMTPS, IMAPS, secure WebSocket, secure databases), you'll need an external TLS-aware client.socket if you really wanted to, but you probably don't want to.fetch's default path uses the OS HTTP stack (WinHTTP). With no protocol flag it negotiates HTTP/2 or HTTP/1.1; the protocol used is reported (and set in $result). That negotiation is best-effort — some systems and servers fall back to HTTP/1.1 regardless, and WinHTTP's client-side HTTP/2 in particular is unreliable. When you need a guaranteed protocol, use --http2 or --http3, which switch to cshw's own native clients (nghttp2 for h2; msquic + nghttp3 for h3) — see "Forcing HTTP/2 or HTTP/3" above. Those are the same libraries cshw's own web servers use on the serving side (Chapter 19), so both ends of a modern-HTTP conversation can be cshw.dig/nslookup equivalent in cshw. Use an external tool if you need DNS-level work.ping reimplementation, no protocol-level packet construction. cshw operates at the TCP/UDP layer; below that, you'd need an external tool.For most "do work over the network" tasks, those limits don't matter. For genuinely low-level networking (writing a new protocol from scratch, doing kernel-level packet capture), shell isn't the right tool anyway.
REMEMBER
cshw's networking commands are designed for the middle ground: "talk to existing services, build small servers, automate API calls." For HTTPS, use fetch. For everything else TLS-protected, external. For UDP and plain TCP, the socket family is plenty. For research-level networking or anything below the transport layer, step outside the shell.
That's networking. Combined with the coroutines and synchronization from Chapters 14 and 15, you can write parallel HTTP scrapers, concurrent TCP servers, custom protocol clients, health-check fleets, and just about any I/O-bound networked tool you'd otherwise reach for a "real language" to build. A surprising amount of network engineering work fits in cshw scripts now, and the result is usually shorter and easier to read than the equivalent in Python or Go.
Chapter 17 introduces the most distinctive feature of cshw: the genai command, which integrates AI providers (Claude, GPT, Azure OpenAI, Ollama, LM Studio, and more) directly into the shell. Suddenly your scripts can ask questions, summarize files, generate code, classify data, and do all the things LLMs are good at — as ordinary command-line operations.
The combination of networking, coroutines, and genai is where cshw starts to look like a very different kind of shell. A parallel LLM analyzer fits in about 30 lines and runs hundreds of completions concurrently. We'll build exactly that.
For now, you've got everything you need to write real networked shell programs. Try the tcpserver examples; spin up a small server, hit it from another shell, watch the interaction. That moment — "wait, I have a working server, and it's a shell script" — is the moment most cshw users decide this isn't really a shell after all. It's a small concurrent runtime that happens to ship with a prompt.
See you in Chapter 17.