سؤال

Suppose we have the following classes:

class Packet implements Serializable { ... };
class OpenConnectionPacket extends Packet { ... };
class DataPacket extends Packet { ... };
class CloseConnectionPacket extends Packet { ... };

Now, I want to be able to send an arbitrary packet like this:

Socket s = ...;
ObjectOutputStream toServer = new ObjectOutputStream(s.getOutputStream());

Packet p = ...;

toServer.writeObject(p);

and recieve it from the other end:

Socket s = ...;
ObjectInputStream fromClient = new ObjectInputStream(s.getInputStream());

Packet p = (Packet) fromClient.readObject();

Is this possible? How? (If it is, I guess is should override the writeObject() and readObject() methods, and maybe have something like a int type; or some enum in the parent class Packet in order to identify each child?)

هل كانت مفيدة؟

المحلول

You don't need to override writeObject() and readObject().

It works by its default implementation until and unless you write your custom logic while serialization if needed.

For more info have a look at below links

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top