Skip to main content
gamedev.net
🔒 Locked

Sending Objects with Serialization

Started by Demx Apr 10, 2011 at 10:27 AM 0 replies 1k views
Original Post
Demx
Demx
Hello,

ive been trying to create a server and client that can communicate by sending objects.

I started by sending a predefined Date object and that works:

Server:


public void run() {
try{
oos.writeObject(new Date());
oos.flush();
oos.close();
client.close();
}catch(Exception e) {}
}

Client:

date = (Date) ois.readObject();
System.out.print("The date is: " + date);


The problem is that i can't get it to work proparly with my objects.

Example class:

public class Player implements Serializable {

private int hp;

public Player(){
hp=0;
}

public void sethp(int hp){
this.hp=hp;
}

public int gethp(){
return hp;
}
}

Server:

Player p = new Player();
p.sethp(15);
oos.writeObject(p);
oos.flush();


Client:

Player p = new Player();
p = (Player) ois.readObject();
hp = p.gethp();
System.out.println("player hp: " + hp );


When i run the programs the client should print the hp value of the object but it gives the following exception : server.Player

Thx for any help
rip-off
rip-off
It would appear that you are calling a method on a null object. Don't do that. Allocate a Player instance using "new".

You shouldn't swallow exceptions like that, particularly with such a generic type. Try to catch the most sensible type you can, in this case IOException. Also, do something with you catch an exception. At the very least log the exception. Better still: either declare the method as throwing the exception or wrap the exception in an unchecked exception (e.g. RuntimeException). In the long run you'll need to handle this properly, as it could indicate the connection is broken or mismatches between the client and server. It probably doesn't make a lot of sense to try to continue to communicate in this case, the client should probably be kicked from the game.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.