Of course it's possible. Just set up nc
as a co-process:
#!/bin/bash -x
# Greets the client with their hostname.
coproc ( nc -l -v localhost 3000 2>&1 )
{
declare "$( sed -e 's/^Connection from \([^ ]*\).*$/client="\1"/' -e 'q' )"
printf 'Hello there, user on %s\n' "$client"
} <&${COPROC[0]} >&${COPROC[1]}
kill "$COPROC_PID"
For something more advanced, like handling HTTP requests:
#!/bin/bash
# Handles one request, then kills nc and restarts
while true; do
coproc ( nc -l localhost 3000 2>&1 )
{
get_http_request_header
process_request
send_http_reply
} <&${COPROC[0]} >&${COPROC[1]}
kill "$COPROC_PID"
done
The commands get_http_request_header
,
process_request
, and
send_http_reply
may be shell functions or separate scripts that you write.
The get_http_request_header
routine would get its standard input from the client connected to nc
and would parse the request, possibly storing it in a temporary file or setting some global variables or in some other way passing the needed information to process_request
.
process_request
may handle compiling the result in whatever way is necessary.
send_http_reply
would print to the client by simply writing to standard output.
Another possible setup where the information on the server side is simply passed along the internal steps through pipes:
#!/bin/bash
# Handles one request, then kills nc and restarts
while true; do
coproc ( nc -l localhost 3000 2>&1 )
{
get_http_request_header |
process_request |
send_http_reply
} <&${COPROC[0]} >&${COPROC[1]}
kill "$COPROC_PID"
done