Reputation: 745
I am sending a file over a socket in Java.
This works pretty well if I close the socket connection after I sent the file, so that the read method returns -1. But I don't want to close the socket, so I need a termination condition. I tried to use inputStream.available, but its not returning the exact number of bytes.
int number;
while((number = inputStream.read(buffer)) != -1) {
fileStream.write(buffer, 0, number);
}
How can I do this?
Upvotes: 1
Views: 45
Reputation: 533492
A standard pattern is to send the length first as say an int
or long
. e.g. DataInput/OutputStream can help you do this.
When you have read this amount of data, you have finished, but the connection is still open and can continue to be used.
Upvotes: 2