Force netcat to send messages immediately (without buffering)
Asked Answered
T

1

6

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.

Truthful answered 10/12, 2015 at 14:40 Comment(3)
Did you do a Google search? "linux netcat no buffer" gave me this as the first result: superuser.com/a/429134/206562Effluent
Yes, I saw this post. However, it didn't work for me when using my script.Truthful
It's worth noting that nc never buffers, it always sends data immediately. It's the python program that's buffering because stdout is not a terminal.Contradict
H
13

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.

Heuser answered 10/12, 2015 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.