gawkinet: Primitive Service
2.8 A Primitive Web Service
===========================
Now we know enough about HTTP to set up a primitive web service that
just says '"Hello, world"' when someone connects to it with a browser.
Compared to the situation in the preceding node, our program changes the
role. It tries to behave just like the server we have observed. Since
we are setting up a server here, we have to insert the port number in
the 'localport' field of the special file name. The other two fields
(HOSTNAME and REMOTEPORT) have to contain a '0' because we do not know
in advance which host will connect to our service.
In the early 1990s, all a server had to do was send an HTML document
and close the connection. Here, we adhere to the modern syntax of HTTP.
The steps are as follows:
1. Send a status line telling the web browser that everything is okay.
2. Send a line to tell the browser how many bytes follow in the body
of the message. This was not necessary earlier because both
parties knew that the document ended when the connection closed.
Nowadays it is possible to stay connected after the transmission of
one web page. This is to avoid the network traffic necessary for
repeatedly establishing TCP connections for requesting several
images. Thus, there is the need to tell the receiving party how
many bytes will be sent. The header is terminated as usual with an
empty line.
3. Send the '"Hello, world"' body in HTML. The useless 'while' loop
swallows the request of the browser. We could actually omit the
loop, and on most machines the program would still work. First,
start the following program:
BEGIN {
RS = ORS = "\r\n"
HttpService = "/inet/tcp/8080/0/0"
Hello = "<HTML><HEAD>" \
"<TITLE>A Famous Greeting</TITLE></HEAD>" \
"<BODY><H1>Hello, world</H1></BODY></HTML>"
Len = length(Hello) + length(ORS)
print "HTTP/1.0 200 OK" |& HttpService
print "Content-Length: " Len ORS |& HttpService
print Hello |& HttpService
while ((HttpService |& getline) > 0)
continue;
close(HttpService)
}
Now, on the same machine, start your favorite browser and let it
point to <http://localhost:8080> (the browser needs to know on which
port our server is listening for requests). If this does not work, the
browser probably tries to connect to a proxy server that does not know
your machine. If so, change the browser's configuration so that the
browser does not try to use a proxy to connect to your machine.