Can you determine how many bytes are present in an accepted Java socket?
The short answer is No. There is nothing in the Socket API that will tell you the overall stream length.
Why? Because if you look at the TCP protocol (as a typical example of a stream transport protocol) there is nothing in the protocol that transmits the stream length ... at the start. Indeed, you only know what the TCP stream length when (and if) the receiving end gets a FIN message. (Refer to the TCP spec or Wikipedia for more details.)
This means that if you need to know the number of (file) bytes that will be sent at the start, you need to handle this at the application protocol layer.
If you use HTTP/1.x, you will need to deal with the 3 variants that Fredrik describes in his answer. And note that in the 3rd one, you won't be able to get the size ahead of time at all. (Of course, if you control the server side, you can ensure that doesn't happen ...)
Note: if you are trying to implement this directly at the socket API level, then the onus is on you to read, (correctly) understand and (correctly) implement the subset of HTTP/1.x that you need. Some of the spec is rather complicated. And it gets potentially even more complicated with newer versions of HTTP ... which are increasingly used by browsers, servers, content delivery networks and so on.
So my advice would be: Don't do it! Use an existing HTTP protocol implementation on both the client and server sides. You will save yourself a lot of time and (mostly) nugatory effort.
If you change your mind about using HTTP, you can basically do what you want. But to achieve the goal of getting the file size at the start of a transfer, the sender will need to send it as part of your custom application protocol.
Non-solution:
Once you get an InputStream
from a Socket
you will see an available()
that tells you how many bytes can be read without blocking. That does NOT tell you the length of the entire stream. Indeed it isn't necessarily even an accurate measure of the number of bytes available. It is best to ignore it and use a (constant) fixed sized buffer for reading. A socket InputStream.read(byte[], ...)
call will return whatever bytes are currently available (up to the buffer size). It will only block if there are zero bytes currently available ... and the stream hasn't been closed.
(The available()
method is pretty much useless. Most valid use-cases can be handled better in other ways; e.g. by using a Selector
.)