• Post Reply Bookmark Topic Watch Topic
  • New Topic

Length of the Socket Input Stream to Read 'OR' End of the Socket Stream  RSS feed

 
Maheshwari Anuj
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have to read a response from a TCP Socket's Input Stream. But I dont know the number of bytes that are coming in response. There is a function called available() that gives the number of bytes available in the stream, but its not reliable, it works some time and sometime not. I also tried to read data till I found "-1" which marks the end of the stream but this is also not working beacuse I think at the server end streams are not getting closed that why I am not getting "-1". Please Help.

Regards,
Anuj Maheshwari
 
Rob Spoor
Sheriff
Posts: 21052
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're right about available - it's not very useful in most cases.

If you don't know how many bytes to receive, perhaps you can make the server first send the number of bytes it will send. You first read that number, then read that many bytes.
 
Glen Divers
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember all available() tells you is the number of bytes that are available to be read (i.e have arrived) at the time you ask. Whether or not the number of bytes returned by available() corresponds to the total size of the data stream is purely co-incidental. Over TCP you have no idea how many bytes are going to arrive together or when. So what you need to do is something like this;

1) Allocate a byte array to the size of the largest possible message. If you can't do this, then you will need to be able to grow you storage array via System.arraycopy.

2) Loop
and store bytes into buffer. When available returns 0 then either the server has finished sending or there are still bytes "in-transit" - you've no way of telling. In this case, all you can do is sleep() for an amount of time appropriate for your application and then test available() again.

Note that even if you do know how long each message is going to be, you still need to loop like this, because there is no guarentee that all the bytes have actually arrived at the point in time when you call inputStream.read().

HTH
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I will use NIO if I have to write this.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!