tags:

views:

201

answers:

1

I am using socket channel and NIO concept to read data from client.
How does Socket Channel knows when reading a file is completed?

ByteBuffer byteBuffer = ByteBuffer.allocate(BUFSIZE);
int nbytes = socketChannel.getChannel().read(byteBuffer);

I am reading the data all at once if the data is small, but if the data is large, I read the data in fragments and finally get the same data now I want to know how does channel understood for end of data.
Is there any way for me to know when the file reading is completed?

+4  A: 

There are three basic options:

  • The protocol could specify that the length of the file should come before the data.
  • The protocol could specify some "end of file" marker (which would have to be invalid for data within the file, of course)
  • The server could close the socket when it had finished: your read call will return -1 to let you know when all the data has been read

Basically the way data is streamed, you can't rely on all the data coming down in a particular number of requests.

What protocol are you using, and can you modify it appropriately? A length prefix is usually the easiest solution.

Jon Skeet