在这段代码中
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
]
为什么先入
http-port: first wait listen-port
而不只是
http-port: wait listen-port
最佳答案
wait
上的listen-port
会阻塞,直到有新的客户端连接为止。一旦发生这种情况,它仅返回listen-port
。然后,后续的first
检索与新连接的客户端相对应的端口。此后,您将拥有两个不同的端口:listen-port
(这是服务器在监听进一步连接的端口)和http-port
(这是用于与新连接的客户端进行通信的端口)。
在这些方面,《 REBOL/Core用户指南》 2.3版中的"Creating TCP Servers"部分仍然是最新的。
关于sockets - Rebol世界上最小的Http服务器: why first wait listen-port?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1291127/