如何Java的TCP / IP套接字报告发送成功或失败的应用程序?

问题描述:

我有Java的TCP / IP套接字一个问题:我的Java应用程序将继续不断地将数据发送到即使服务器被关闭(没有正确的TCP / IP断开连接)在此期间的服务器

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.

我用下面的code发送数据:

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!");
}

在another堆栈溢出问题,我发现下面的回答:

In another Stack Overflow question, I found the following answer:

的TCP / IP(以及为此的java插座)
  将保证你要么
  成功发送数据,或者得到一个
  错误(在Java中的情况除外)
  最终。

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.

是我的code足够越来越了解不能够成功地把我的字符串中的TCP / IP堆栈或我需要另外做些什么?

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.

我没有提到什么(因为我认为这是当时没有相关的)是,我试图做到这一点在Android上。

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.

数周的测试后,虽然,它似乎是Android的执行标准的Java网络类的行为是从Oracle JRE非常不同。在Android上,这显然是不可能可靠地检测,如果连接已经关闭,即使我关闭它自己。 [流] .WRITE()将尝试写几分钟。所以在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.

另外这个问题的答案将正常工作与Oracle JRE。再次感谢!

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.