简体   繁体   中英

Java Serializing different objects

I want to make a small network game of two clients sending messages to eachother. I'm new to sockets and serialization but I read that sending serialized objects via sockets is the way to do.

My problem is, I have multiple types of messages. One might be a simple chat message, the other one a turn (message) like a "NewObjectMessage" or "MoveObjectMessage"...

In tutorials I always read something like

MyClass myClass = (MyClass) objectinputstream.readObject();

which does a casting to the one specific class I put in the stream on the other side.

Question is: is there any way of determining what kind of message I get? I'm looking for something like

stream.peekObject() 

or something in order to see it's type.

Or is the common way to send two messages and the first one is only a declaration telling what comes next? But what happens if some packages get mixed up and the next object is not the one I was asking for?

So what is the best way to communicate between the clients in a way of eg moving an object and creating an object (or writing a message etc.)?

Thanks for your help!

Just read the object as an Object, and use instanceof to see what type it is.

Or have the objects all implement a common interface with an action method and just cast to the interface and call the method.

I think what you are looking for is object.getClass().getName(); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM