我使用ObjectStreams在服务器和客户端之间进行通信。一切都很好。但现在我到了一个点,我想将ArrayList发送到客户端。类卡是可序列化的。
如果我第一次将ArrayList发送到客户端,则客户端从服务器发送ArrayList。
如果我更改Serverside上的ArrayList并将其发送到客户端,则客户端仍会获得旧版本。
以下是我使用的Codesnippets:
###Server###
for ( CardPlayer cp: players_in_game){
cp.setHand(new ArrayList<Card>(0));
System.out.println("Generate an empty ArrayList of Cards for : " + cp.getName() );
cp.getHand().add(deck.takeCardFromTop());
System.out.println("Add a card to hand of Player : " + cp.getName());
cp.getHand().add(deck.takeCardFromTop());
System.out.println("Add a card to hand of Player : " + cp.getName());
cp.getHand().add(deck.takeCardFromTop());
System.out.println("Add a card to hand of Player : " + cp.getName());
}
for ( CardPlayer cp: players_in_game ){
String cmd = "updatecards";
try {
cp.getOos().writeObject(cmd);
cp.getOos().flush();
cp.getOos().writeObject(cp.getHand());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for ( CardPlayer cp: players_in_game){
cp.getHand().add(deck.takeCardFromTop());
System.out.println("Add a card to hand of Player : " + cp.getName());
cp.getHand().add(deck.takeCardFromTop());
System.out.println("Add a card to hand of Player : " + cp.getName());
}
for ( CardPlayer cp: players_in_game ){
String cmd = "updatecards";
try {
cp.getOos().writeObject(cmd);
cp.getOos().flush();
System.out.println("Server is sending an ArrayList with "+ cp.getHand().size() +" Cards");
cp.getOos().writeObject(cp.getHand());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
###Client###
while (gameIsStillActive) {
String cmd = (String) ois_game.readObject();
if (cmd.equals("updatecards")) {
ArrayList recievedCards = (ArrayList) ois_game.readObject();
System.out.println(this.name + ": Recieved a ArrayList with " + recievedCards.size() + " Cards.");
}
}
###console###
Generate an empty ArrayList of Cards for : Harald
Add a card to hand of Player : Harald
Add a card to hand of Player : Harald
Add a card to hand of Player : Harald
Generate an empty ArrayList of Cards for : Stephan
Add a card to hand of Player : Stephan
Add a card to hand of Player : Stephan
Add a card to hand of Player : Stephan
Generate an empty ArrayList of Cards for : Dummy
Add a card to hand of Player : Dummy
Add a card to hand of Player : Dummy
Add a card to hand of Player : Dummy
Harald: Recieved a ArrayList with 3 Cards.
Stephan: Recieved a ArrayList with 3 Cards.
Dummy: Recieved a ArrayList with 3 Cards.
Add a card to hand of Player : Harald
Add a card to hand of Player : Harald
Add a card to hand of Player : Stephan
Add a card to hand of Player : Stephan
Add a card to hand of Player : Dummy
Add a card to hand of Player : Dummy
Server is sending an ArrayList with 5 Cards
Harald: Recieved a ArrayList with 3 Cards.
Server is sending an ArrayList with 5 Cards
Stephan: Recieved a ArrayList with 3 Cards.
Server is sending an ArrayList with 5 Cards
Dummy: Recieved a ArrayList with 3 Cards.
Das Deck hat noch17 Karten