DatagramChannel.close() keeps port open on Windows

前端 未结 2 887
我在风中等你
我在风中等你 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: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( )
    }
    

提交回复
热议问题