Как закрыть соединение клиента с сервером без краша сервера и клиента?

Мне нужно, чтобы при авторизации клиента в чате включался таймер, по истечению которого клиент должен отключиться от сервера. Я сделал таймер в отдельном треде и он работает и функцию выполняет- закрывает соединение. Однако из-за того, что в основном потоке программа висит на методе чтения (блокирующем), то при закрытии соединения вылетает исключение SocketException: Connection reset. Не могу сообразить, как безопасно закрыть это соединение.

 public void openConnection() throws IOException {
    socket = new Socket("localhost", 8999);
    in = new DataInputStream(socket.getInputStream());
    out = new DataOutputStream(socket.getOutputStream());
    new Thread(() -> {
        try {
            waitAuth();
            readMessages();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeConnection();
            System.exit(0);
        }
    }).start();
}

private void waitAuth() throws IOException {

    while (true) {
        runTimer(2);
        final String message = in.readUTF();
        Command command = Command.getCommand(message);
        String[] params = command.parse(message);
        if (command == AUTHOK) {
            isAuth = true;
            final String nick = params[0];
            controller.setAuth(true);
            controller.addMessage("Успешная авторизация под ником " + nick);
            break;
        }
        if (command == ERROR) {
            Platform.runLater(() -> controller.showError(params[0]));
            continue;
        }
//        if (command ==TIME_IS_GONE) {
//            Platform.runLater(() ->controller.showError("Время вышло! =)"));
//            closeConnection();
//        }

    }
}

private void runTimer(int maxSec) {
    new Thread (() -> {
        int timer = maxSec;
        while (timer>0) {
            try {
                Thread.sleep(1000);
                timer--;
                System.out.println(timer);
                if (isAuth) {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (!isAuth) {
           closeConnection();
        }
    }).start();
}

Ответы (0 шт):