Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force netcat to send messages immediately (without buffering)

Tags:

linux

netcat

I'm using a python script to generate data using standard print() arguments. The output from the script should then be sent to localhost tcp socket 9999.

python script.py | nc -lk 9999

On the client side I'm listening to localhost tcp socket 9999 to verify everything is working fine.

nc localhost 9999

And yes, it's working. But it looks like nc is buffering some messages before sending them. As a result, I get huge delays on the client side, which is not acceptable for my application: I need the data asap.

Is there a way to disable the buffer?

I noticed that if I send more messages, the delay decreases. However, this isn't really a solution for me.

like image 572
Tim Avatar asked Dec 19 '22 21:12

Tim


1 Answers

You can use the stdbuf command:

stdbuf -o0 python script.py | stdbuf -i0 nc -lk 9999

or the -u Unbuffered option for python:

python -u script.py | stdbuf -i0  nc -lk 9999

I/O buffering is, unless a program explicitly handles it on it's own, handled by the libc. stdbuf influences that behaviour. Further reading man stdbuf.

like image 192
hek2mgl Avatar answered Feb 05 '23 18:02

hek2mgl