Я делаю онлайн-игру для школьного задания. Два пользователя подключаются к серверу и играют в кооперативную пошаговую игру, где они пытаются победить врага. Когда я отправляю объект GameCharacter с клиента на сервер ПОСЛЕ первого раза, он не сохраняет обновленные значения, а только исходные значения, которые были отправлены в первый раз. Назначение ДОЛЖНО включать также многопоточность и шаблон наблюдателя.
Ниже приведены фрагменты классов, которые создают проблему. Это от экземпляра 1 клиента к 1 серверу.
//Sending from the client to the server
synchronized public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getNewValue() instanceof GameCharacter)
{
//First time the code is run, all values are initialized. Current hp is 350.
//Second time the code is run, several values are updated. Current hp is 100
GameCharacter test = (GameCharacter) evt.getNewValue();
try
{
this.player = test;
System.out.println(test.getCurrentHp() + " Is the characters current hp in Client");
dos.writeObject(test);
} catch (IOException ex)
{
JOptionPane.showMessageDialog (null, "Error sending character to server" );
}
}
}
//The server immediately after receiving the object
//This is defined in the constructor
private ObjectInputStream ois;
@Override
public void run()
{
Object superTempHolder = null;
while (true)
{
try
{
superTempHolder = ois.readObject();
} catch (IOException ex)
{
System.out.println("I don't know how to receive.");
fixIOException(ex);
} catch (ClassNotFoundException ex)
{
System.out.println("I don't know what that is.");
fixClassNotFoundException(ex);
}
//If statement added for testing purposes
if (superTempHolder instanceof GameCharacter)
{
GameCharacter tester = (GameCharacter) superTempHolder;
System.out.println(tester.getCurrentHp() + " Is the current hp of the character in InputListener");
}
listener.propertyChange(new PropertyChangeEvent(this, Integer.toString(this.id), null, superTempHolder));
}
}
Вывод от клиента
350 Is the characters current hp in Client
100 Is the characters current hp in Client
Вывод с сервера
350 Is the current hp of the character in InputListener
350 Is the current hp of the character in InputListener
Это единственный способ, с помощью которого эта программа может отправить GameCharacter с клиента на сервер. GameCharacter полностью сериализован, и я не уверен, откуда он берет 350, когда отправляет второй раз, поскольку на клиенте фактически существует только один экземпляр GameCharacter.
В конечном счете, проблема заключается в следующем:правильно отправляет объект, но не обновленные значения, и сервер каким-то образом считывает информацию, которой больше не существует.