How is SocketChannel known when reading a file?

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

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

      

I read the data immediately if the data is small, but if the data is large, I read the data in chunks and finally get the same data now, I want to know how the pipe is understood for the end of the data.
Is there a way to know when the file has finished reading?

+1


a source to share


1 answer


There are three main options:

  • The protocol may indicate that the length of the file must be before the data.
  • Some "end of file" marker may be specified in the protocol (which of course must be invalid for data in the file)
  • The server can close the socket when it's finished: your call read

    will return -1 so you know when all the data has been read.


Basically, streams of data are transmitted, you cannot rely on all data coming in for a certain number of requests.

What protocol are you using and can you change it accordingly? The length prefix is โ€‹โ€‹usually the simplest solution.

+4


a source







All Articles