Search code examples
javasocketsiobytenio

Can't find NewLine with ByteBuffer


Using some SocketChannels with NIO I am passing the key through this method to get a message. However, whenever it passes it displays a newline and I cannot for the life of me find out why and where. Any help would be appreciated.

public void messageHandler(SelectionKey key) throws IOException
    {
        SocketChannel ch = (SocketChannel) key.channel();
        StringBuilder sb = new StringBuilder();
        buf.clear();
        int read = 0;
        while( (read = ch.read(buf)) > 0 ) {
            buf.flip();
            byte[] bytes = new byte[buf.limit()];
            buf.get(bytes);
            sb.append(new String(bytes));
            buf.clear();
       }
}

EDITED: I left a print statement in there by mistake for my own debugging. That has nothing to do with it. I output this to sb.toString() and a new line is contained in there.


Solution

  • I assume the other end is sending a new line and it is in the bytes

    Using println() (which auto-flushed by default) can be replaced with print() and flush();

    BTW You can use ByteBuffer.wrap(bytes) to avoid copying the bytes twice.

    for(byte b: bytes)
        if(b == 10 || b == 13) 
             System.err.println("Contains newline");