1

I have written a small program in java, which reads from a socket inputstream in an extra thread, this is the run-method of the reading thread, currently I run two of them, one for a test-client and one for a test-socket, both on my laptop (localhost).

@Override
public void run() {
    try {
        while (!this.isInterrupted() && !this.connection.isClosed()) {
            //read some data, store them into a byte[] and pass them to a processing method
        }
    } catch (IOException e) {
        e.printStackTrace(); //TODO Logger
    }
}

I tested the code and got a SocketClosedException. After testing and running it over ten times again, I did not get any exception or similar. For my understanding, the read(...) method blocks until I read something right? So how can I escape the thread, if the inputstream is closed? Is there even any need? Like I said, I was not able to reproduce the exception again.

EDIT: I managed to create the exception again. I got:

java.net.SocketException: Socket closed

and after that

java.net.SocketException: Connection reset

Any ideas how to prevent them?

F_Schmidt
  • 902
  • 1
  • 11
  • 32
  • For some reason the socket is being closed before you begin the read. Is there any reason you can't just catch the error and handle it? i.e. reset the connection or wait until the connection is open again – SevvyP Jul 20 '20 at 20:39
  • I guess, that the WHILE-condition is checked and the socket connection still is opened. Then the socket connection closes and the thread inside now inside the while fails reading. But how can i prevent that effect? – F_Schmidt Jul 20 '20 at 20:42
  • 1
    *How do I stop reading from inputstream if socket is closed without error in thrad?* you don,t - you catch an IOException and proceed accordingly. – Antoniossss Jul 20 '20 at 20:43
  • yep, that makes sence. In the catch-clause I terminated the executorService to terminate the thread in a clean way. – F_Schmidt Jul 20 '20 at 22:42
  • The `isClosed` method doesn't tell you whether the connection has been closed, only whether *you* have closed *this socket.* You can shutdown the socket for input from your closing thread to get a cleaner exit from this code. – user207421 Jul 21 '20 at 00:53

0 Answers0