I use netcat to run a tiny development webserver through the bash, which is able to handle one connection at once.
Netcat is started as follows (-k
to make it survive multiple connections):
nc -kl 3000
A bash script processes the browser's request which is received by netcat, and builds the response, which is sent back to the browser through the same netcat instance.
Everything works as expected, but sometimes, the browser does not get the file it requested. My suspicion: If a connection is closed before the response is sent completely, the response's remainder is sent as response to the following request (it, of course, not belongs to).
Proof
- Terminal 1 (Server):
nc -kl 3000
- Terminal 2 (simulates Browser):
nc localhost 3000
- Type
hello\n
in terminal 1. - Terminal 2 prints
hello\n
. - Do Ctrl+C in terminal 2 to end the connection.
- Type
world\n
in terminal 1. - Run
nc localhost 3000
in terminal 2 again (new connection). - Terminal 2 immediately shows
world\n
even thoughworld\n
was actually sent when no connection existed, meant as second response line in the first connection.
Required behavior: Ignore all bytes that are passed to netcat if no connection exists.
Is it possible using netcat? (I prefer a tool like netcat as it comes pre-installed on all machines.)
input
andoutput
):coproc nc -kl "$port"; input="${COPROC[0]}"; output="${COPROC[1]}"
– Traceablenetcat
is a well-known tool and often even comes pre-installed (as well as thebash
), I chose it. If there is no other pre-installed tool worthy of consideration on a pristine linux installation (Ubuntu in my case), andncat
fits my needs, I will stick with it. For other projects I usewebpack
's dev server or a small JavaScript runningexpress
. – Traceablepython -m SimpleHTTPServer <port>
(which becomeshttp.server
in python 3.x) which is rather easy to customize. – Moencat
and if it does not work, I will use Python's simple HTTP server. – Traceable