2

I'm working on a Server which will have to hold hundreds pending tcp-connections, each of which only rarely transmits/receives actual data. I'd prefer doing this with non-blocking / selector based java.nio sockets rather then having hundreds of blocking threads in my application.

From java.nio I get a SocketChannel and a Signal when it is readable. Its int .read(ByteBuffer dst) method reads the available number of Bytes into a ByteBuffer.

I expect my Clients to send messages, one Message per line, terminated with a \n Character.

Obviously a read-Operation may produce only parts of a Message, a completed and an unfinished of even multiple Messages at once. Furthermore the ByteBuffer operates on bytes, not characters, so the read Operation might also yield an incomplete String with split UTF-8 Characters.

I'm now searching for a way to write the read bytes into a Buffer-Structure which I then can read completed lines from, but which will not block when a UTF-8-Character or Line has not yet arrived completely.

java.io's PipedOutputStream/PipedInputStream together with an InputStreamReader and BufferedReader nearly fulfill these requirements, but they are blocking in a way, that calling int .read() or String .readLine() on the BufferedReader will block if a not finished UTF-8 Character or Line is present in the input.

I'm now looking for the cleanest Equivalent that can be operated non-blocking. Any dependency, Apache Commons or other 3rd-Party dependencies are ok.

Here's a basic non-blocking Server Example to get started: https://gist.github.com/MaZderMind/12fe3b370e654f31ea22aaa540f5a741

  • As a Follow-Up: I implemented a Solution using the `java.nio` Decoder-Facilities and a custom crafted Segmented Buffer: https://gist.github.com/MaZderMind/0be1dea275ea25b39dc753583d742851 This is far from the clean solution I hoped for, but it works as desired. If no cleaner solution pops up, I'll add Tests and report back here. – Peter Körner Apr 21 '19 at 21:29
  • Hundreds is peanuts. I would use block sockets and `readLine()` for this. Ten times as simple. – user207421 Apr 22 '19 at 02:56

0 Answers0