Rebol Smallest Http Server in the World: why first wait listen-port?
Question
In this code
web-dir: %./www/ ; the path to rebol www subdirectory
listen-port: open/lines tcp://:80 ; port used for web connections
buffer: make string! 1024 ; will auto-expand if needed
forever [
http-port: first wait listen-port
while [not empty? client-request: first http-port][
repend buffer [client-request newline]
]
repend buffer ["Address: " http-port/host newline]
parse buffer ["get" ["http" | "/ " | copy file to " "]]
parse file [thru "." [
"html" (mime: "text/html") |
"txt" (mime: "text/plain")
]
]
data: read/binary web-dir/:file
insert data rejoin ["HTTP/1.0 200 OK^/Content-type: " mime "^/^/"]
write-io http-port data length? data
close http-port
]
Why first in
http-port: first wait listen-port
instead of just
http-port: wait listen-port
Solution
The wait
on the listen-port
blocks until a new client connects. Once that happens, it simply returns listen-port
. The subsequent first
then retrieves port corresponding to the newly connected client. After this, you have two distinct ports: listen-port
, which is the port the server listens on for further connects, and http-port
, which is the port for talking to the newly connected client.
The section "Creating TCP Servers" from the REBOL/Core Users Guide for version 2.3 is still perfectly up to date in those regards.
OTHER TIPS
wait
blocks until listen-port has activity, then returns listen-port
.
Thus, first
takes and returns the first line of data from listen-port
.
The documentation explains (however briefly).