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

I am using the SocketChannelJava class for a client / server application. I can send and receive 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 use US-ASCII decoding. How can I overcome this type of problem?

Thanks Deepak

+3
source share
3 answers

The read operation does not guarantee the reading of all available data and does not read data at all if the SocketChannel is in non-blocking mode. In the above case, you may need more than one call to read all transmitted data.

, . , ( ..) .

+1

, ByteBuffer .

SocketChannel, , , . sysouts ByteBuffer

while(ByteBuffer.hasRemaining(){
    socketChannel.write(buffer) //writing data
    System.out.printline(socketChanel.remaining() + " : bytes to go");
}

.

0

, , , \n - . , , . , <= 127.

I would suggest that your application does not work as you think, and that you are reading lines that suggest \ n termination somewhere in your code.

Can you put code to write and read a line. that is, how do you determine when a line ends?

0
source

Source: https://habr.com/ru/post/1708537/


All Articles