为什么在没有尝试I / O的情况下检测TCP套接字是否被对等端正常关闭是不可能的? [英] Why is it impossible, without attempting I/O, to detect that TCP socket was gracefully closed by peer?

查看:161
本文介绍了为什么在没有尝试I / O的情况下检测TCP套接字是否被对等端正常关闭是不可能的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为最近问题的后续跟进,我想知道为什么在没有尝试在TCP套接字上读/写的情况下,在Java中检测套接字是否被对等端正常关闭是不可能的?无论是否使用pre-NIO Socket 或NIO SocketChannel ,情况似乎都是如此。

As a follow up to a recent question, I wonder why it is impossible in Java, without attempting reading/writing on a TCP socket, to detect that the socket has been gracefully closed by the peer? This seems to be the case regardless of whether one uses the pre-NIO Socket or the NIO SocketChannel.

当对等体正常关闭TCP连接时,连接两端的TCP堆栈都知道这一事实。服务器端(启动关闭的那个)最终处于状态 FIN_WAIT2 ,而客户端(未明确响应关闭的那个)最终结束在州 CLOSE_WAIT 。为什么 Socket SocketChannel 中没有方法可以查询TCP堆栈以查看底层TCP连接已被终止?是不是TCP堆栈没有提供这样的状态信息?或者这是一个设计决定,以避免昂贵的内核调用?

When a peer gracefully closes a TCP connection, the TCP stacks on both sides of the connection know about the fact. The server-side (the one that initiates the shutdown) ends up in state FIN_WAIT2, whereas the client-side (the one that does not explicitly respond to the shutdown) ends up in state CLOSE_WAIT. Why isn't there a method in Socket or SocketChannel that can query the TCP stack to see whether the underlying TCP connection has been terminated? Is it that the TCP stack doesn't provide such status information? Or is it a design decision to avoid a costly call into the kernel?

在已经发布了这个问题的答案的用户的帮助下,我想我看到了问题可能来自哪里。未明确关闭连接的一方最终处于TCP状态 CLOSE_WAIT 意味着连接正在关闭并等待方发出自己的关闭操作。我认为 isConnected 返回 true isClosed 是公平的返回 false ,但为什么不存在类似 isClosing

With the help of the users who have already posted some answers to this question, I think I see where the issue might be coming from. The side that doesn't explicitly close the connection ends up in TCP state CLOSE_WAIT meaning that the connection is in the process of shutting down and waits for the side to issue its own CLOSE operation. I suppose it's fair enough that isConnected returns true and isClosed returns false, but why isn't there something like isClosing?

以下是使用pre-NIO套接字的测试类。但是使用NIO可以获得相同的结果。

Below are the test classes that use pre-NIO sockets. But identical results are obtained using NIO.

import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
  public static void main(String[] args) throws Exception {
    final ServerSocket ss = new ServerSocket(12345);
    final Socket cs = ss.accept();
    System.out.println("Accepted connection");
    Thread.sleep(5000);
    cs.close();
    System.out.println("Closed connection");
    ss.close();
    Thread.sleep(100000);
  }
}


import java.net.Socket;

public class MyClient {
  public static void main(String[] args) throws Exception {
    final Socket s = new Socket("localhost", 12345);
    for (int i = 0; i < 10; i++) {
      System.out.println("connected: " + s.isConnected() + 
        ", closed: " + s.isClosed());
      Thread.sleep(1000);
    }
    Thread.sleep(100000);
  }
}

当测试客户端连接到测试服务器时输出即使在服务器启动连接关闭后仍保持不变:

When the test client connects to the test server the output remains unchanged even after the server initiates the shutdown of the connection:

connected: true, closed: false
connected: true, closed: false
...


推荐答案

我经常使用套接字,主要是使用选择器,虽然不是网络OSI专家,但根据我的理解,在Socket上调用 shutdownOutput()实际上是在网络上发送一些东西(FIN)唤醒另一方的Selector(C语言中的相同行为)。在这里你有检测:实际检测到你尝试时会失败的读取操作。

I have been using Sockets often, mostly with Selectors, and though not a Network OSI expert, from my understanding, calling shutdownOutput() on a Socket actually sends something on the network (FIN) that wakes up my Selector on the other side (same behaviour in C language). Here you have detection: actually detecting a read operation that will fail when you try it.

在你提供的代码中,关闭套接字将关闭输入和输出流,无法读取可能的数据,从而丢失它们。 Java Socket.close()方法执行正常断开连接(与我最初的想法相反),因为输出流中剩余的数据将被发送然后是FIN 以表示其结束。 FIN将由另一方确认,因为任何常规数据包将 1

In the code you give, closing the socket will shutdown both input and output streams, without possibilities of reading the data that might be available, therefore loosing them. The Java Socket.close() method performs a "graceful" disconnection (opposite as what I initially thought) in that the data left in the output stream will be sent followed by a FIN to signal its close. The FIN will be ACK'd by the other side, as any regular packet would1.

如果您需要等待另一方要关闭它的套接字,你需要等待它的FIN。为实现这一目标,您必须检测 Socket.getInputStream()。read()< 0 ,这意味着您关闭套接字,因为它关闭其 InputStream

If you need to wait for the other side to close its socket, you need to wait for its FIN. And to achieve that, you have to detect Socket.getInputStream().read() < 0, which means you should not close your socket, as it would close its InputStream.

从我在C中所做的,现在在Java中,实现这样的同步关闭应该是这样的:

From what I did in C, and now in Java, achieving such a synchronized close should be done like this:


  1. 关闭套接字输出(在另一端发送FIN,这是此套接字将发送的最后一件事)。输入仍然是打开的,所以你可以读取()并检测远程 close()

  2. 读取套接字 InputStream ,直到我们收到另一端的reply-FIN(因为它将检测FIN,它将经历同样优雅的diconnection过程) 。这在某些操作系统上很重要,因为只要其中一个缓冲区仍包含数据,它们就不会实际关闭套接字。它们被称为ghost套接字并在操作系统中使用描述符编号(现代操作系统可能不再是问题)

  3. 关闭套接字(通过调用 Socket.close()或关闭其 InputStream OutputStream

  1. Shutdown socket output (sends FIN on the other end, this is the last thing that will ever be sent by this socket). Input is still open so you can read() and detect the remote close()
  2. Read the socket InputStream until we receive the reply-FIN from the other end (as it will detect the FIN, it will go through the same graceful diconnection process). This is important on some OS as they don't actually close the socket as long as one of its buffer still contains data. They're called "ghost" socket and use up descriptor numbers in the OS (that might not be an issue anymore with modern OS)
  3. Close the socket (by either calling Socket.close() or closing its InputStream or OutputStream)

如以下Java代码段所示:

As shown in the following Java snippet:

public void synchronizedClose(Socket sok) {
    InputStream is = sok.getInputStream();
    sok.shutdownOutput(); // Sends the 'FIN' on the network
    while (is.read() > 0) ; // "read()" returns '-1' when the 'FIN' is reached
    sok.close(); // or is.close(); Now we can close the Socket
}

当然双方必须使用相同的关闭方式,或者发送部分可能始终发送足够的数据以保持循环忙(例如,如果发送部分仅发送数据和永远不会读取以检测连接终止。这是笨拙的,但你可能无法控制它。)

Of course both sides have to use the same way of closing, or the sending part might always be sending enough data to keep the while loop busy (e.g. if the sending part is only sending data and never reading to detect connection termination. Which is clumsy, but you might not have control on that).

正如@WarrenDew在他的评论中指出的那样,丢弃数据程序(应用程序层)在应用程序层引起非正常断开连接:尽管所有数据都是在TCP层接收的(循环),但它们将被丢弃。

As @WarrenDew pointed out in his comment, discarding the data in the program (application layer) induces a non-graceful disconnection at application layer: though all data were received at TCP layer (the while loop), they are discarded.

1 :来自 Java中的基础网络:见图。 3.3 p.45,以及整个§3.7,pp 43-48

1: From "Fundamental Networking in Java": see fig. 3.3 p.45, and the whole §3.7, pp 43-48

这篇关于为什么在没有尝试I / O的情况下检测TCP套接字是否被对等端正常关闭是不可能的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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