Blocking listener is very simple but in can't be interrupted by calling thread. So there's no point in that:
Future<Socket> future = executor.submit( Listeners.createListener( PORT ) );
try {
Socket socket = future.get( 1, TimeUnit.SECONDS );
} catch( TimeoutException e ) {
future.cancel( true );
}
Listener will stay active and PORT will be bound still. The reason is in usage of the uninterruptible ServerSocket.accept().
In contrary non-blocking listener is more sophisticated but it can be interrupted by calling thread. So you can do that:
Future<Socket> future = executor.submit( Listeners.createListener( PORT ) );
try {
Socket socket = future.get( 1, TimeUnit.SECONDS );
} catch( TimeoutException e ) {
future.cancel( true );
}
Listener will be terminated and PORT will be freed.
May be useful for Linux/MacOS users :) It's fully interruptible too.
Process process = Listeners.createNetCatListener( PORT );
...
process.destroy();
Add following to your pom.xml:
<repositories>
<repository>
<id>dddpaul</id>
<url>http://dl.bintray.com/dddpaul/maven</url>
</repository>
<repository>
<id>jcenter</id>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.github.dddpaul</groupId>
<artifactId>network-listeners</artifactId>
<version>1.0</version>
</dependency>
</dependencies>