For my first networking project, I am working on a simple client/server chat, using TCP.
The idea was, make the communication lines (i.e. threads), and send packets over them (an id and packet-specific information).
It seems it works, but not consistently.
Here are some pictures to describe the problem:
Not working:
Working:
Left is server, right is client.
I get both of these result only by running it - no code changes involved. It seems roughly 25% of the time, it works.
The server has two lines at the top. The first is how many bytes were received. The second lists the bytes.
On the bottom of the client, it lists what bytes were written. The actual communication is through a DataOutputStream through the socket's OutputStream. I used another DataOutputStream with a ByteArrayOutputStream. In every place the first writes, the second does as well. It seems, then, that the bytes written does not change.
As for the bytes themselves. The first 0 is the packet id (there is only one packet currently). The load of this packet was a single string, a name. It seems writeUTF writes the length of the string as a short (two bytes, the next 0 and 3), followed by the characters.
The reason it fails when the bytes don't make it is that it reads the packet id correctly, tries reading the short for the length, but there is nothing left.
What might be causing this inconsistency?