1

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();
1
  • 2
    Maybe it's stuck because it's waiting for more data to come. Was the stream closed at the other end? Do you know how much data you are expecting? Commented Feb 3, 2012 at 13:30

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What ive read "-1" means EOF and that is why im checking if its bigger than 0. am I doing it the wrong way?
read tries to read 1024 chars, and if there are less chars in the stream, it waits for more chars to come. you may take a look to ByteArrayInputStream and DataInputStream concrete classes.
I might take a look at ByteArray and Data. I do not know how many bytes there are in the file.
Alright I did some workarounds and managed to be able to add some statements to find the EOF. Thanks for advice
0

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.

2 Comments

The problem is that it can contain any character.
Could you maybe add a length number to the beginning of the file from the sender, and have the receiver read the length first, and then continue to read the rest until the specified length was read?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.