Closing an Asynchronous Channel in Java NIO

Suppose I have a simple nio based java server. For example (simplified code):

while (!self.isInterrupted()) {
  if (selector.select() <= 0) {
    continue;
  }

  Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
  while (iterator.hasNext()) {
    SelectionKey key = iterator.next();
    iterator.remove();
    SelectableChannel channel = key.channel();

    if (key.isValid() && key.isAcceptable()) {
      SocketChannel client = ((ServerSocketChannel) channel).accept();
      if (client != null) {
        client.configureBlocking(false);
        client.register(selector, SelectionKey.OP_READ);
      }
    } else if (key.isValid() && key.isReadable()) {
      channel.read(buffer);
      channel.close();
    }
  }
}

So, this is a simple single-threaded non-blocking server.

The problem is the following code.

channel.read(buffer);
channel.close();

When I close the channel in the same thread (the thread that accepts the connection and read data), everything works fine. But I had a problem when the connection closed in another thread. for example

((SocketChannel) channel).read(buffer);
executor.execute(new Runnable() {
   public void run() {
     channel.close();
   }
});

In this scenario, I ended the socket in TIME_WAIT state on the server and ESTABLISHED on the client. Thus, the connection does not close gracefully. Any ideas what's wrong? What did I miss?

+3
source share
5 answers

TIME_WAIT , , . , , RST, . Java-, . - RST, -, .

, - ? , OS , - . , .

+1

, , . . catch (Throwable t) ( , )

0

, Mac.

, TIME_WAIT 1 , ( telnet ).

, , . java?

0

, , . BSD/OS X poll(), , .

, - , , , - BSD/OS X.

0

.

Java NIO , accept() , accept(). , , Java NIO - . , , , , . , , , , accept() .

. , , .

[ ]

.

:

  • 300+ .
  • 24 , .. -, .jpg.
  • ( dialup, / ) - ACK TCP/IP , (- )
  • 1 . ( , , .) , 24K .
  • ( ).

, 500 -1500 , .

, , . . .

[ ] . , , . , , .

( Gnarly , java- - .

. , IO . , TCP/IP 8K-64K . TCP/IP . , .

, , java io read.

, , , , ", " . , .

, java-, .

0
source

Source: https://habr.com/ru/post/1707997/


All Articles