Sign in to follow this  
Demx

Sending Objects with Serialization

Recommended Posts

Demx    389
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:

[code]
public void run() {
try{
oos.writeObject(new Date());
oos.flush();
oos.close();
client.close();
}catch(Exception e) {}
}
[/code]
Client:
[code]
date = (Date) ois.readObject();
System.out.print("The date is: " + date);
[/code]

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

Example class:
[code]
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;
}
}
[/code]
Server:
[code]
Player p = new Player();
p.sethp(15);
oos.writeObject(p);
oos.flush();
[/code]

Client:
[code]
Player p = new Player();
p = (Player) ois.readObject();
hp = p.gethp();
System.out.println("player hp: " + hp );
[/code]

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 :)

Share this post


Link to post
Share on other sites
rip-off    10979
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this