Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming response on a socket in Java

I have a Java socket server and the the connection socket working just fine. What I need help with is streaming a response back to the client.

I get the output stream with socket.getOutputStream(). How can I make it so that when I write to the output stream it is immediately sent, but in the future on the same connection I can send another chunk of data.

I tried simply using write and write in conjunction with flush, but I don't really know what I am doing...

like image 624
Alec Gorge Avatar asked Nov 29 '25 17:11

Alec Gorge


2 Answers

Depending on native implementation, the socket may have a buffer, and not send the bytes the second you call write(). flush() however, will force the bytes to be sent. Typically it is good practice to send larger chunks rather than byte by byte (for streaming you generally start by building up a buffer on the receiver's side). Optimal network usage is likely to be to send as large packets as possible (limited by MTU). To have a local buffer in java, wrap the socket outputstream in a BufferedOutputStream.

like image 135
Martin Algesten Avatar answered Dec 02 '25 05:12

Martin Algesten


flush() will force the data to be sent to the OS. The OS can buffer the data and so can the OS on the client. If you want the OS to send data earlier, I suggest you try turning Nagle's Algorithm off. socket.setTcpNoDelay(true); However, you will find that OS/driver parameters can still introduce some buffering/packet coelesing.

If you look at Sun's JDK 6 java.net.SocketOutputStream you will see the flush() method does nothing. This is not guarenteed to be the case on all platforms and a flush() may be required.

like image 28
Peter Lawrey Avatar answered Dec 02 '25 07:12

Peter Lawrey