如何在 Java 应用程序中检测 FIN - tcp 标志? [英] How to detect FIN - tcp flag in java application?

查看:33
本文介绍了如何在 Java 应用程序中检测 FIN - tcp 标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两台计算机之间建立了持久的 TCP 连接(第二个不在我的控制之下).第二台计算机可以随时发送 FIN 标志,首先必须关闭连接(将 FIN 标志发送回第二台计算机).

I have long-lasting TCP connection between two computers (second not under my control). Second computer can send FIN flag at every moment, and first must close connection corrent (send FIN flag back to second computer).

我怎么知道第二台计算机发送了一个 FIN 标志,以及何时必须触发我的 Java 应用程序的 socket.close() 方法?

How can I know that the second computer sending a FIN flag and when I must cause socket.close() method of my Java application?

推荐答案

通常,您必须读取连接,当 EOF 或适当的 IOException 返回 -1 时,您可以关闭连接.注意:SocketTimeoutException 不代表连接已关闭.

Normally, you have to read the connection and when this returns -1 for EOF or an appropriate IOException, you can close the connection. Note: SocketTimeoutException doesn't mean the connection is closed.

一个例子.

boolean ok = false;
try {
  int b = in.read();
  ok = b >= 0;
  if (!ok)
     throw new EOFException();
} finally {
  if (!ok)
     in.close();
}

这篇关于如何在 Java 应用程序中检测 FIN - tcp 标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆