I am having a problem with Java TCP/IP sockets: my Java application will continue endlessly to send data to a server even if the server gets switched off (without a proper TCP/IP disconnect) in the meantime.
I am using the following code to send the data:
PrintWriter out = PrintWriter(socket.getOutputStream(), true);
out.write("text");
if (out.checkError()) {
System.err.println("Error sending string!");
}
In another Stack Overflow question, I found the following answer:
TCP/IP (and therefor java sockets)
will guarantee that you either
successfully send the data OR get an
error (exception in the case of java)
eventually.
Is my code sufficient for getting informed about the TCP/IP stack not being able to successfully send my string or do I need to do something additionally?
Btw: was it correct to open a new question even though the other question was similar? It did not answer my question satisfactorily and I was only able to add a new answer, not a new comment.
解决方案
What I didn't mention (as I thought it was not relevant at that time) is that I am trying to do this on Android.
After several weeks of testing, though, it seems that Android's implementation of the standard Java networking classes is behaving very differently from the Oracle JRE. On Android, it is apparently impossible to reliably detect if the connection has been closed, even if I closed it myself. [Stream].write() will try writing for several minutes. So on Android, it appears that you will always need to send your own keep-alives (and check for reception!) for detecting a broken connection.
The other answers to this question will work fine with the Oracle JRE. Thanks again!
If anyone can provide further information on this topic, please do so.