简体   繁体   中英

Java TCP server - android client packet loss

I'm trying to create a basic multiplayer game for android, using a Java TCP server and Android client. The problem is slow speed when sending TCP packets. When I put Thread.sleep(100) then it works.

server side:

for(int i = 0; i<50; i++) {
    client.send("test_" + i);
}

client just received (~3 packet)
test_0
test_1

server with sleep:

for(int i = 0; i<50; i++) {
        client.send("test_" + i);
        Thread.sleep(100);
}

client received ~45

EDIT: client side:

while (true) {
if (!running)
    break;
inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"), 2 * 1024);
String rawRecervied = inFromServer.readLine();
if (rawRecervied == null) {
    close();
    break;
}
final String recervied = rawRecervied.substring(2); // for skip utf bom chars
new Thread() {
    public void run() {
        listener.dataRecervied(recervied);
        Log.e("TCP recervied", recervied); // debug
    }
}.start();
}

Maybe the key is in the BufferedReader . You're in a loop, and constantly create a BufferedReader to check if something has been sent from the server. Once data is detected, you start processing it, but data keeps coming, and is buffered in the BufferedReader . After processing the initially detected data, you create again a BufferedReader but, what happens with all the data that was already buffered in the BufferedReader created before? Maybe it's lost.

Could you try creating the BufferedReader outside the loop?

If it is a one-way protocol where packet loss is acceptable then use UDP instead of TCP as it is cheaper in terms of network resources. I think this is not your case however. If TCP, then implement a basic flow control where the client acknowledges the received packet with echoing its ID back to the server.

You should also revise your client and server code because this behaviour might be in the way you implemented that client.sent(..) . Do you always close and reopen the connection? Or what?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM