views:

1609

answers:

1

Hi all,

If I'm only WRITING to a socket on an output stream, will it ever block? Only reads can block, right? I am asking because someone told me writes can block but I only see a timeout feature for the read method of a socket - socket.setSOTimeout(). It doesn't make sense to me that a write could block but I'd like to hear for sure from more than one person.

Please let me know. Thanks, jbu

+2  A: 

A write on a Socket can block too, especially if it is a TCP Socket. The OS will only buffer a certain amount of untransmitted (or transmitted but unacknowledged) data. If you write stuff faster than the remote app is able to read it, the socket will eventually back up and your write calls will block.

EDIT: responding to following questions as comments ...

So is there a mechanism to set a timeout for this? I'm not sure what behavior it'd have...maybe throw away data if buffers are full? Or possibly delete older data in the buffer?

There is no mechanism to set a write timeout on a java.net.Socket. There is a Socket.setSoTimeout() method, but it affects accept() and read() calls ... and not write() calls. Apparently, you can get write timeouts if you use NIO, non-blocking mode, and a Selector, but this is not as useful as you might imagine.

A properly implemented TCP stack does not discard buffered data unless the connection is closed. If you implement your app to resend the same data after taking a write timeout, the receiving end is likely to get some or all of the data twice. So, the only safe thing to do after a timeout on write() is to shut down the connection.

EDIT 2: By contrast, if you use a UDP socket, write() calls won't block for any length of time. But the downside is that if there are network problems or the remote application is not keeping up, messages will be dropped on the floor with no notification to either end. In addition, you may find that messages are delivered to the remote application out of order. It will be up to you (the developer) to deal with these issues.

Stephen C
So is there a mechanism to set a timeout for this? I'm not sure what behavior it'd have...maybe throw away data if buffers are full? Or possibly delete older data in the buffer?
jbu