0

I have a Java NIO socket server.

The server is getting JSONObjects from remote clients. i'm using the SocketChannel.read(ByteBuffer) method in order to read from the channel. each message ends with '\n' which marks the end of the current message.

my problem is that sometimes the read() method read more bytes and reach after the '\n'.. is there a way for me to read from the SocketChannel only until the '\n' is found ? i thought about maybe byte by byte read (i just couldn't find documents on how to implement it..)?

any other solutions ?

Asaf Nevo
  • 11,338
  • 23
  • 79
  • 154

1 Answers1

2

Process the bytes from your ByteBuffer up to and including the '\n', so the buffer's position is the first byte after the '\n', then call ByteBuffer.compact(). Any bytes which were past the '\n' will remain in the buffer and the next read will append to them.

VGR
  • 40,506
  • 4
  • 48
  • 63
  • that's not a bad idea, but i thought about leaving inside the SocketChannel the remaining data to read, so the selector will find that that are new messages to read later.. it is important because the mechanisim of my server is that for each messages - a thread from a thread pool will execute – Asaf Nevo Dec 24 '12 at 07:22
  • To do that, you probably would, as you suggested, have to read one byte at a time, which I imagine wouldn't have good performance. I think instead of relying on a SelectionKey being readable to know when you have a message, you'll need to look for '\n' in the buffer after each read. Which you probably had to do anyway, since a bulk read is never guaranteed to read in an entire line in one call (and could even read more than one line). – VGR Dec 24 '12 at 12:53