Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send and then read \n using SocketChannel in Java

Tags:

java

nio

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

like image 672
Deepak Avatar asked Dec 01 '25 05:12

Deepak


1 Answers

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.

like image 80
Neal Maloney Avatar answered Dec 03 '25 22:12

Neal Maloney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!