I´m searching for an efficient way to read bytes from a socket channel using Java NIO. The task is quite easy, I have a solution, though I´m searching for a cleaner and more efficient way to solve this. Here´s the scenario:
- Data is read from a socket channel
- This data is a UTF-8 encoded string
- Every line is ended by \r\n, the length is unknown up front
- After every line read, I want to do something with the message
My solution reads the data byte per byte and compares every byte to my marker (which is has the value 10 in UTF-8 code pages). Here´s the code:
ByteBuffer res = ByteBuffer.allocate(512);
boolean completed = false;
try {
while (true) {
ByteBuffer tmp = ByteBuffer.allocate(1);
if(soc.read(tmp) == -1) {
break;
}
// set marker back to index 0
tmp.rewind();
byte cur = tmp.get();
res.put(cur);
// have we read newline?
if (cur == 10) {
doSomething(res);
res.clear();
}
}
} catch(Exception ex) {
handle(ex);
}
Even though this does the job, there might be a better way, that doesn't need those per byte comparisons after every iteration.
Thanks for your help!