Sockets: BufferedOutputStream or just OutputStream?

▼魔方 西西 提交于 2019-11-27 23:59:44

问题


In order to get the fastest transfer speeds over TCP in Java, which is better:

Option A:

InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();

Option B:

BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());

I've read that performance takes a hit when writing over 8 KiB to OutputStream, it was recommended that it'd be written to it in small chunks not pver 8 KiB at a time. 8 KiB is the default buffer size of a BufferedOutputStream.

However I've also read that when transfering data over the net it's good to flush out the bytes as quickly as possible. Meaning that using a buffer and writing in small chunks adds a unneeded overhead.

So, option A or option B? Which works best?

Right now I'm guessing option A gives highest transfer speeds while consuming a lot more CPU than option B. Option B might be better since it doesn't go that much slower but saves a lot of CPU.

--

Bonus question: Is it a good idea to touch the TCP window size? For example by setting it to 64 KiB:

socket.setReceiveBufferSize(65536);
socket.setSendBufferSize(65536);

I tried setting it to 128 KiB on a test machine since I read that it could increase speeds but when the server got a couple of connections the CPU were at 100% instead of ~2% like when I left it alone. I guess 128 KiB is way too high unless you've got a good server that can handle that rush in traffic, but is it smart to set it to something like 32 KiB? I think the default was 8 KiB there for me.

("socket" is "java.net.Socket")


回答1:


I don't know where you read all that nonsense but it is completely back to front. The more you write at a time to a TCP connection the better, and the more you read from it at a time ditto. I would always use a buffered stream, reader, or writer between the application and the socket streams. There are some cases like SSL where directly writing a byte at a time can cause a 40x data explosion.

Is it a good idea to touch the TCP window size? For example by setting it to 64 KiB

You can't 'touch the TCP window size'. You can increase its maximum value via the APIs you mention, and that is indeed a good idea.



来源:https://stackoverflow.com/questions/11373259/sockets-bufferedoutputstream-or-just-outputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!