How does TCP_NODELAY affect consecutive write () calls?

TCP_NODELAY is an option for quickly sending TCP packets regardless of their size. This is a very useful option when speed matters, but I'm curious what it will do with it:

Socket socket = [some socket]; socket.setTcpNoDelay(true); OutputStream out = socket.getOutputStream(); out.write(byteArray1); out.write(byteArray2); out.write(byteArray3); out.flush(); 

I tried to find out what flush actually does on a SocketOutputStream , but as far as I know, it does nothing. I was hoping he would tell the socket "send all your buffered data NOW", but unfortunately not, it is not.

My question is: are these 3 byte arrays sent in the same packet? I know that you don't have much control over how TCP creates the network packet, but is there a way to tell the socket (at least try) to pack these byte arrays, so avoid network overhead? Can I manually pack byte arrays and send them with a single call to write help?

+5
source share
2 answers

My question is: are these 3 byte arrays sent in the same packet?

How you turned off the Nagle algorithm is almost certainly not, but you cannot be 100% sure.

I know that you do not have much control over how TCP creates a network packet, but is there any way to tell the socket (at least try) to pack these byte arrays

Yes. Do not disable the Nagle algorithm.

so that network overhead can be avoided? Can I manually pack byte arrays and send them in one call to write help?

Yes, or just put the socket output stream in a BufferedOutputStream and call flush() when you want the data to be sent according to your real code. You are correct that flush() does nothing in the output stream of the socket, but it discards the BufferedOutputStream.

+6
source

Can I manually pack byte arrays and send them in one call to write help?

Yes, send them all at once to write. This will maximize the likelihood that your bytes will be sent in one packet.

Of course, you will never know, since there are too many variables - different OSs and many different network devices between you and your colleague, but if you give the OS the opportunity to put everything together, you will usually try to.

If you disable nagle and make separate system calls (remember, the OS manages sockets, not your application or java), you ask the OS to send them separately. The OS has no idea that you are going to rewrite the record again with some data.

+1
source

Source: https://habr.com/ru/post/986416/


All Articles