I'm trying to set up a minimal web server using netcat (nc). When the browser calls up localhost:1500, for instance, it should show the result of a function (date in the example below, but eventually it'll be a python or c program that yields some data).
My little netcat web server needs to be a while true loop in bash, possibly as simple as this:
while true ; do echo -e "HTTP/1.1 200 OK\n\n $(date)" | nc -l -p 1500 ; done
When I try this the browser shows the currently available data during the moment when nc starts. I want the browser displays the data during the moment the browser requests it, though. How can I achieve this?
Best Answer
Try this:
The
-c
makes netcat execute the given command in a shell, so you can use echo. If you don't need echo, use-e
. For further information on this, tryman nc
. Note, that when usingecho
there is no way for your program (thedate
-replacement) to get the browser request. So you probably finally want to do something like this:Where
yourprogram
must do the protocol stuff like handling GET, sending HTTP 200 etc.