I transfer data from server to client via SocketChannel
. The buffer size is 10kbyte = 10240 bytes. After getting the ByteBuffer
I get a string from it, translate the string into a JSONObject
and then I process the data. So the fact is that ByteBuffer
often comes beaten and cannot be converted to JSONObject, although there are no errors at the time of writing / reading from the channel. How to transfer data, respecting their integrity? I was thinking of putting a checksum into the packet, but this would require additional computational resources. Tell me how to be in this situation.
And so, the reading code:
ByteBuffer buffer = ByteBuffer.allocate(1024); public String readLine() { StringBuilder sb = new StringBuilder(); int k; do { buffer.clear(); k = socketChannel.read(buffer); buffer.flip(); CharBuffer charBuff = charset.decode(buffer); for(int i=0; i<charBuff.limit(); i++) sb.append(charBuff.get()); } while(k == 1024); return sb.toString().trim(); }
Record Code:
public void writeLine(String string) { socketChannel.write(charset.encode(string)); }
for
loopfor
append
, or transfer its length in bytes to Json. - avp