简体   繁体   中英

Java sending objects by sockets in threads

I'm doing small game Tron Bikes.

I have MainFrame class

Bike bike1, bike2;
private void startGameAsServer(){
    bike1 = new Bike();
    bike2 = new Bike();
    communication.sendBike(bike1);
    communication.sendBike(bike2);
}
...
public synchronized void receiveBike(Bike receive){
    //depends if I'm server or client I save receive to bike1 or bike2
}
...

Second class Communication

...
ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream input = new ObjectInputStream(client.getInputStream());
...
public void sendBike(Bike send){
    try {
        output.writeObject(send);
        output.flush();
        System.out.println("Send bike");
    } catch (IOException ex) {
    }
}
...
private void listen(){
    listening = new Thread(new Runnable() {

        @Override
        public void run() {
            while(true){
                try {
                    Bike readBike = (Bike)input.readObject();
                    System.out.println("Receive bike");
                    MainFrame.getInstance().receiveBike(readBike);
                } catch (IOException | ClassNotFoundException ex) {
                    break;
                }
            }
        }
    });

    listening.start();
}
...

When I start game, it works fine. On server both bikes are created, send to client, and then game start. But when in client I turn to side, I send one bike back to server, and here is problem.

In server in method receiveBike bike1 and bike2 is null... And if I write to bike1 or bike2 nothing happend. Even many times in a second, data from bike1 a nd bike2 are loaded to draw game panel. It looks, that data are loaded from old objects.

Like in method receiveBike we change completely different objects... I'm so desperate, I don't know what I'm doing wrong...

You need to call ObjectOutputStream.reset() or use writeUnshared(), for the reasons given in the Javadoc. The stream is conserving object graph integrity by giving you back the same object every time. These methods circumvent that.

NB you need to catch EOFException separately and break out of your reading loop when you catch it. Any other exception should be logged.

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