Next: Concurrent Clients Server, Previous: Time of Day Server, Up: Communications Samples [Index]
Very simple web server, giving a Goodbye, World! message:
file i, o, s; tcpip_listen(s, 8080, 0); while (1) { accept(i, o, s, 0); f_(o, "HTTP/1.1 200 OK\n" "Content-Type: text/html; charset=UTF-8\n" "Content-Length: 106\n\n" "<!DOCTYPE html><html><head><title>baby bye-bye</title></head><body><h1>Goodbye, world!</h1></body></html>\n"); f_flush(o); }
Some browsers are not happy with an immediately closed connection, reason why the files are kept open until the next client.
File (socket) polling is not required by this application, but it is by many others. Together with randomly colored text and delayed connection closing:
void serve(dispatch w, file s, list colors) { file i, o; text color; accept(i, o, s, 0); color = colors[drand(3)]; f_(o, "HTTP/1.1 200 OK\n" "Content-Type: text/html; charset=UTF-8\n" "Content-Length: ", 236 + ~color, "\n\n" "<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>" "<style>body { background-color: #111 }" "h1 { font-size:4cm; text-align: center; color: black;" " text-shadow: 0 0 2mm ", color, "}</style></head>" "<body><h1>Goodbye, world!</h1></body></html>\n"); # keep connection for two more seconds. w.schedule(date().now.offset(2, 0), f_close, i); } integer main(void) { dispatch w; file s; tcpip_listen(s, 8080, 0); w.watch(s, serve, w, s, list("blue", "green", "red", "yellow")); w.press(); 0; }
See The Control Library.