开发者

Extracting <CRLF>-Strings from a ByteBuffer - I'm getting all confused

I've been sitting with this problem for some hours now without getting it to work the way I want it to work.

I'm creating a server which reads data from a telnet client. The server uses java.nio (ServerSocketChannel) and reads into a ByteBuffer. After each read() I'm calling a method which is suppose to extract all lines (seperated by "\r\n") from the ByteBuffer and leave the (if any) remaining bytes in a way so the next read() puts t开发者_如何学JAVAhem in the correct position.

Example:

read() reads 6 bytes, the ByteBuffer now contains "Hi\r\nHo". What I want to do is to extract all completely recieved strings, in this example "Hi\r\n". I want to "Ho" to be left in the ByteBuffer, shifted so that the "H" is at position 0, so that when I call read() next time and recieve "w are you?\r\n", it will be put at the correct place in the ByteBuffer.

I created a small test program but I can't seem to get it to do it correct: http://pastebin.com/eun1nV2N

Try different test strings ("HI", "HI\r\n", "HI\r\nHEY\r", etc) and you'll see when it fails. (I used the eclipse debug tool to inspect variables)


Try wrapping the ByteBuffer an InputStream and a BufferedReader, then you should be able to use readline to get the lines one by one.


  1. Flip the buffer.
  2. Call get() until you have the \r\n, storing the get() result of course.
  3. Compact the buffer.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜