Skip to content

Instantly share code, notes, and snippets.

@mcSw4p
Created August 10, 2017 03:43
Show Gist options
  • Save mcSw4p/491b2742bb9c9964e2138b456047a70e to your computer and use it in GitHub Desktop.
Save mcSw4p/491b2742bb9c9964e2138b456047a70e to your computer and use it in GitHub Desktop.
// You would put this is some sort of daemon thread
// Lets you change the AtomicBoolean value to close the SocketServer
AtomicBoolean running = new AtomicBoolean(true);
ServerSocket server = new ServerSocket();
// Set the socket server timeout to something small so the server errors out fast after you
// flip the atomic boolean
server.setSoTimeout(1000); // 1 sec
try{
while (running.get()) {
try {
// Accept the socket
Socket socket = server.accept();
// do your normal socket handling thing
}catch(SocketTimeoutException e){} // Do nothing. Server socket timed out
}
}catch(IOException e){
// print stacktrace
}finnally{
if(!serverListener.isClosed()){ // Not closed yet right?
try {
serverListener.close(); // close...
}catch (SocketException e) {} catch (IOException e) {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment