简体   繁体   中英

Java nio partial read

My goal is to send different kind of messages from client to server, and it will be text based. The thing I am uncertain of is how to del with partial reads here. I will have to be sure that I get a whole message and nothing more.

Do anyone have experience with that?

Here is what I have so far:

    private void handleNewClientMessage(SelectionKey key) throws IOException {
    SocketChannel sendingChannel = (SocketChannel) key.channel();

    ByteBuffer receivingBuffer = ByteBuffer.allocate(2048);
    int bytesRead = sendingChannel.read(receivingBuffer);
    if (bytesRead > 0) {
        receivingBuffer.flip();

        byte[] array = new byte[receivingBuffer.limit()];
        receivingBuffer.get(array);
        String message = new String(array);

        System.out.println("Server received "  +message);           
    }
    selector.wakeup();
}

But I have no way of "ending" the message and be certain to have one full message.

Best regards, O

You can never be sure you won't read more than one message unless you only read one byte at a time. (Which I don't suggest).

Instead I would read as much as you can into a ByteBuffer and then parse it to find the end of the message eg a newline for text.

When you find the end of a line extract it and convert it to a String and process it. repeat until you have a partial message (or nothing left)

If you find you have only part of a message, you compact() (if position() > 0) when you have and try to read() some more.

This will allows you to read as many messages at once as you can but can also handle incomplete messages.

Note: You will need to keep the ByteBuffer for a connection so you know what partial messages you have read before.

Note: this is will not work if you have a message which is larger than your buffer size. I suggest using a recycled direct ByteBuffer of say 1+ MB. With direct ByteBuffers only the pages of the ByteBuffer which are used get allocated to real memory.

If you are concerned about performance I would re-use your byte[] where possible. You only need to re-allocate it if you need more space than you have already.

BTW, You might find using a BufferedReader with Plain IO is much simpler to use, but still performance well enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM