Reputation: 4820
I build a client side (SocketChannel) which is getting big messages (the size of each message is ~1MB-~2MB). How can I get the message ? I'm using selector. When the key isReadable I want to read all the packets of the receiving message. How can I know that the receiving packets belongs to one message and not to the other message ?
Upvotes: 0
Views: 987
Reputation: 4357
The safest way to do this is to know in advance the size of each message. If you can change the server protocol to send the size of the message just before the message itself, then all you have to do in the client is to read the size first, eventually allocate enough memory for that size in a ByteBuffer for instance, then read the data until you have the desired number of bytes.
If you cannot change the server protocol, then there has to be some way to recognize the start or end of a message, like a specific header or footer. Then you need to keep reading data until you reach the footer or the next header, depending on what you have.
Also keep in mind that for large messages, you will likely not have all the data in a single read(). You'll need to keep your selection key interested in OP_READ operations, adding a chunk of data into your buffer with each read(), until all the data has been read from the channel.
Upvotes: 1