简体   繁体   中英

Java NIO SocketChannel read pre-defined bytes number

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 ?

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.

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