Deepak
Deepak

Reputation: 437

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

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

Upvotes: 3

Views: 3550

Answers (3)

ist_lion
ist_lion

Reputation: 3209

I think you're having an issue with the ByteBuffer on the allocation.

I've had issues previously with SocketChannel where data just seemed to get held up. I would recommend doing some sysouts on ByteBuffer

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

This may be a step in the right direction to isolating the issue.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533442

If you are sending data as binary as you suggest, there is no reason that \n would be treated differently to any other byte. If it were things like images would get corrupted all the time. The encoding shouldn't make any difference if you have using characters <= 127.

I would suggest your application isn't working the way you think it is and that you are reading strings which assume a \n termination somewhere in your code.

Can you post the code for writing and reading the string. i.e. how do you determine when the string ends?

Upvotes: 0

Neal Maloney
Neal Maloney

Reputation: 1184

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.

Upvotes: 1

Related Questions