Sample Header Ad - 728x90

How do I write a simple request/response tcp server using `nc`?

2 votes
2 answers
3678 views
I’m trying to write a request/response TCP server to handle a small number of very simple commands. I'm using a shell script to be as portable as possible, avoiding compilation or requiring specific runtimes of a programming language. I would like it to be able to respond to the client saying the result of the command, meaning the response has to be dynamic. I'm currently trying to use nc:
mkfifo commands
mkfifo nc_responses

nc -k -l 47201 >commands nc_responses
done 
Here's the output of calling it in a second shell:
$ nc localhost 47201 <<< 'command 1'
$ nc localhost 47201 <<< 'command 2'
Ran command 1
$ nc localhost 47201 <<< 'command 3'
Ran command 2
$ nc localhost 47201 <<< 'command 4'
Ran command 3
As you can see, the response lags the request by one. Can anyone see a way to fix that, so that the response is dynamically generated from the request? (For context - this is using bash on macOS, with macOS's built-in nc)
Asked by Robert Elliot (121 rep)
Dec 22, 2020, 12:56 PM
Last activity: Aug 30, 2024, 05:02 AM