java套接字实验总结,如何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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值