簡體   English   中英

非阻塞模式下的ServerSocketChannel無法正確關閉

[英]ServerSocketChannel in non-blocking mode is not closing properly

當ServerSocketChannel在非阻塞模式下使用並在選擇器中注冊時,以下channel.close()調用不會立即關閉套接字,並且在LISTENING狀態的netstat輸出中仍然可見。

一個簡單的測試用例。

// windows 7 / jdk1.8.0_71 x64

@Test
public void test() throws Exception {
    Selector selector = Selector.open();

    for (int i = 0; i < 3; i++) {
        System.out.printf("Trial %d\n", i);
        reopen(selector);
    }
}

private void reopen(Selector selector) throws Exception {
    ServerSocketChannel channel = ServerSocketChannel.open();
    channel.configureBlocking(false);
    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.bind(new InetSocketAddress("127.0.0.1", 17777));

    // --- if channel is not registered with selector the following close() method works fine
    SelectionKey selectionKey = channel.register(selector, SelectionKey.OP_ACCEPT);

    // --- trying to cancel the registration in selector - doesn't help
    // selectionKey.cancel();
    // selector.wakeup();

    // --- trying to configure the socket as blocking - doesn't help
    // selectionKey.cancel();
    // channel.configureBlocking(true);

    // --- trying to register the channel in other selector - doesn't help
    // selectionKey.cancel();
    // Selector nullSelector = Selector.open();
    // channel.register(nullSelector, 0);
    // nullSelector.close();

    channel.close();

    // PROBLEM: after close() has returned I still see this port is listening
    //
    //     C:\Dev>netstat -nao | grep 17777
    //     TCP    127.0.0.1:17777        0.0.0.0:0              LISTENING       xxxx
    //
    // so on the next bind I get an exception: java.net.BindException: Address already in use: bind

    // --- it helps!!! but I don't want to because there could multiple server sockets on the same selector
    // selector.close();

    // --- trying to shake-up the selector - doesn't help
    // selector.wakeup();

    // --- trying to wait some time - doesn't help
    // Thread.sleep(10000);
}

正確關閉ServerSocketChannel的唯一機會是關閉選擇器本身。 但是選擇器用於其他套接字,我不想關閉它。

如何在不關閉選擇器的情況下正確關閉ServerSocketChannel? 或者如何等待直到關閉?

UPD:問題僅在Windows上發生。 找到解決方案並將其發布在下面的評論中。

在嘗試了許多選項之后,我發現此代碼有幫助:

channel.close();

selector.selectNow();

要么

selectionKey.cancel();
selector.selectNow();

channel.close();

但我不知道它為什么起作用。 可能有人會解釋這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM