DatagramChannel.close() keeps port open on Windows

前端 未结 2 862
我在风中等你
我在风中等你 2021-01-21 18:33

I\'m implementing a Discover process that:

  • Open a UDP socket to listen for broadcast response on a given port
  • Send some requests (and expect later respons
相关标签:
2条回答
  • 2021-01-21 18:48

    Some parts of a channel close are deferred to the next select() if the channel is registered with a Selector. It is documented somewhere in the forest of Selector, AbstractSelector, SelectorSpi, SelectableChannel, AbstractSelectableChannel, where I can never find it when I need it. If you're within the select loop and thread when you close the channel, you can make it immediate by calling selectNow().

    0 讨论(0)
  • 2021-01-21 18:55

    I did get some errors but the socket get closed properly... which is oki for my needs

    No, in case you've got errors your channel is NOT closed properly.

    You have to do close in the finally clause of your try block.

    Selector selector = Selector.open();
    try
    {
      DatagramChannel channel = DatagramChannel.open();
    
      try
      {
        channel.configureBlocking(true);
        channel.socket().bind(
          new InetSocketAddress(InetAddress.getLocalHost(), 9005)
        );
        SelectionKey clientKey = channel.register(selector, SelectionKey.OP_READ);
        clientKey.cancel();
      }
      finally
      {
        channel.close();
      }
    }
    finally
    {
      selector.close( )
    }
    
    0 讨论(0)
提交回复
热议问题