1

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 e.g. moving an object and creating an object (or writing a message etc.)?

Thanks for your help!

1
  • Nope. You need a protocol! For example, you could send a String first that describes the Object being sent? Of you could use something like STOMP which has headers, into which you can place metadata... Commented Jan 17, 2016 at 22:34

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Would work - bit messy if there are many different types of message.
Okay, so at least I might use it like an ordinary "local" object? Okay, well, at least this might work. Still, I'm not sure this is the way to do...
Well, since no one seems to know a better solution I vote for it. Thanks alot!
@BoristheSpider if there weren't different types of message it wouldn't be necessary and the question wouldn't exist.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.