I have read all around the Stack, but I cannot find a working solution to determine the packet size and set the array of bytes to match that length to receive a correct amount of bytes for one message at once.
DataInputStream in = new DataInputStream(socket.getInputStream());
while(true) {
short myShortStreamSize = in.readShort();
byte[] payload = new byte[myShortStreamSize];
in.readFully(payload);
Log.i("Foo", new String(payload));
}
That doesn't work for me.
My TLS server is made with Node.js. Normally Node.js TLS module handles the packets in the way if I use the same module to connect to the server it's enough to use socket.write("message")
and the Node.js client understands the sizes already so you don't need to define it yourself. It will write that message to the console without issues. As I mentioned that my server is TLS. I'm not sure if these have something to do with my issue, but would be awesome to make it work.
My goal is to receive one message at once without cutting it into pieces. If I send "Good morning, today is a sunny day!" I want my Java/Android client to read it from start to end without mixing it up with other packets.
... size of TLS packet ... determine the packet size ... receive one message at once
There is no "TLS packet". There is a TLS record which has the length in the first 2 bytes. This TLS record might be split into multiple TCP fragments or TCP fragments might also contain multiple TLS records in full, in half or whatever. These TCP fragments then might even be cut into multiple IP packets although TCP tries hard to avoid this.
And your plain text "message" itself might end up being spread over multiple TLS records since the size of such a record might be smaller than the message. Depending on your application and TLS stack it might also be mixed together with other "messages".
In other words: what you want is impossible. Unless you somehow know already the size of your message before reading it you cannot rely on reading the full message and also only this message. Neither TCP nor TLS preserve any message "boundaries" you might have imagined when crafting your writes but which have no actual representation in the payload.