Question

Client and server communicate via two streams (ObjectOutputStream, ObjectInputStream);

Multithreaded server sends data of the players every second to synchronize the client with the server. And data about every players actions are sent to clients.

In this loop the client receives the data and decide what to do with them. And sometimes there is an error in this line Object data = in.readObject();

I think the error occurs when the two threads on the server at the same time trying to send data to the client. Is this true?

while(true) {
    Object data = in.readObject();
    if (data instanceof ControlShareData) {
        ControlShareData c = (ControlShareData)data;
        if (c.playerId == Game.player.id) {
            Game.player.keyChange(c);
        }
        else {
            for (Player p: Game.enemies) {
                if (c.playerId == p.id) {
                    p.keyChange(c);
                }
            }
        }
    }
    else if (data instanceof ShareData) {
        ShareData sd = (ShareData)data;

        Game.syncing(sd);
    }
}

Server side looks like this:

first thread: (exec every second for all clients)

p.out.writeObject(new ShareData(players, Wrd.boxes));
p.out.flush();

and players thread (one player - one thread):

public void sendInfoAboutKey(int keyCode, boolean value) {
    try {
        for (Player p: Game.players) {
            p.out.writeObject(new ControlShareData(keyCode, value, id));
            p.out.flush();
        }
    } catch (IOException e) {
        Server.removePlayer(this);
    }
}
Was it helpful?

Solution

Yes, you are correct - to solve this problem you could synchronize your access to each ObjectOutputStream. Which there should only be one of per client, by the way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top