Hello, I had a problem with TCP. My networking code works fine when I run the server and client on my pc, but when my friend tries to join the game, or I join his, the data gets corrupted and the received length is wrong when a 22kb packet is sent in one go.
I changed it so I send the tcp data one byte at a time, flushing the output stream after each byte. I guess this is quite inefficient / slow? the main thing is that now it works.
So, what is optimal? and right now, I am waiting in an infinite loop for the next byte, like so (because I know how many bytes are expected, that was sent earlier), this is bad right? is there a better way? (read() blocks anyway, but I had to put it in a loop because each time flush is called i get a -1 on the receiving end)
private byte[] receiveData(int length) throws IOException
{
byte[] data = new byte[length];
int offset = 0;
while (offset < length)
{
int len = 1;
int result = -1;
do
{
result = is.read(data, offset, len);
}
while(result == -1);
offset += len;
}
return data;
}
Here’s the server code
private void sendData(byte[] data)
{
try
{
int offset = 0;
while (offset < data.length)
{
int len = 1;
os.write(data,offset, len);
os.flush();
offset += len;
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
Thanks,
roland