warbio
warbio

Reputation: 466

Java - Stuck when reading from inputstream

Hello I am currently working with sockets and input/output streams. I have a strange problem with my loop I use to send bytes. For some reason it get stuck when it tries to read from the inputstream when it is supposed to stop. Does anyone have any idea whats wrong?

     int bit;
     final byte[] request = new byte[1024];

     if (response instanceof InputStream)
     {   
         while ((bit = response.read(request)) > 0) { // <-- Stuck here
             incoming.getOutputStream().write(request,0,bit);
             incoming.getOutputStream().flush();
         }
     }   
     incoming.close();

Upvotes: 1

Views: 6169

Answers (2)

DRiFTy
DRiFTy

Reputation: 11369

What I've done in the past to leave each side open is to add a termination character to the end of each message that you wouldn't expect to see in the message. If you are building the messages yourself then you could use a character such as a ; or maybe double pipes or something ||. Then just check for that character on the receiving end. Just a workaround. Not a solution. It was necessary in my case but may not be for you.

Upvotes: 0

vulkanino
vulkanino

Reputation: 9124

InputStream.read blocks until input data is available, end of file is detected, or an exception is thrown.

You don't catch the exception, and don't check for EOF.

Upvotes: 2

Related Questions