Skip to content

Instantly share code, notes, and snippets.

@ibaca
Created August 19, 2014 19:20
Show Gist options
  • Save ibaca/7af03683c36fb032e13d to your computer and use it in GitHub Desktop.
Save ibaca/7af03683c36fb032e13d to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Semaphore;
public class SocketCloseDetection {
public static void main(String[] args) throws IOException, InterruptedException {
final ServerSocket serverSocket = new ServerSocket(6677);
final Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
new Thread(new Runnable() {
@Override
public void run() {
try {
final Socket accept = serverSocket.accept();
semaphore.acquire();
System.out.println("closing server socket in 3 seconds...");
Thread.sleep(3000);
accept.close();
semaphore.release();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}).start();
Thread.sleep(100);
System.out.println("client socket, wait until read...");
final Socket socket = new Socket("localhost", serverSocket.getLocalPort());
final InputStream inputStream = socket.getInputStream();
semaphore.release();
final int read = read(inputStream);
socket.close(); // mark as closed
System.out.println("inputStream.read=" + read);
System.out.println("bound=" + socket.isBound());
System.out.println("connected=" + socket.isConnected());
System.out.println("closed=" + socket.isClosed());
System.out.println("input shutdown=" + socket.isInputShutdown());
System.out.println("output shutdown=" + socket.isOutputShutdown());
Thread.sleep(5000);
}
public static int read(InputStream inputStream) throws IOException {
try {
return inputStream.read();
} catch (Exception ignore) {
ignore.printStackTrace();
return -2;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment