I am using the SocketChannel Java class for a client/server application. I can send and retrieve data. But if my data contains '\n' then I do not read the correct data. For example
sending data = "Hi dear"
receiving data = "Hi dear"
sending data = "Hi dear\n\n i am fine"
receiving data = "Hi dear"
sending data = "Hi dear\\n\\n i am fine"
receiving data = "Hi dear\n\n i am fine"
ByteBuffer byteBuffer = ByteBuffer.allocate(BUFSIZE);
int nbytes = socketChannel.getChannel().read(byteBuffer);
I am using US-ASCII decoding. How can I overcome this type of problem?
Thanks, Deepak
The read operation doesn't guarantee to read all of the available data, nor read any data at all if the SocketChannel is in non blocking mode. In the case above, you may need more than one call to read all of the data transmitted.
You need some sort of way for the receiving code to know when it has read all of the data. This means either having the sender send information about the content of the data (length etc.) as part of an agreed protocol, or by using the Channel for only one chunk of data and reading the Channel until it is closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With