2

I am using Netty4 to develop a Client/Server application. I need to transfer different types of Java Objects (POJOs) from the client to server and vice-verse. I am bit confused on how the client or the server would know the type of the java object received? Also, is it a good idea to transfer Java objects like this (or) try to use a format like JSON/XML/Proto-buffers and convert the message to Java Object after receiving?

2 Answers 2

1

You could use Protobuf or just Serialization. Netty ships decoder/encoder for both o them.

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

3 Comments

My question is more like, How would i know the object type that I received? Should I check with "instanceof"? Thanks.
It should be part of your protocol. If you use something like serialization you can just check for the instanceof. If you build your own binary protocol for example you could encode it in the tcp stream etc.
any examples of using protobufs?
1

Objects are more of a concept that exist virtually in memory and you can not transfer them as they are. You have to use some way of serialization.

Serialization results in a stream of data that describes the state and type of your data in a way that all involved sides can understand.

Java comes with a serialization mechanism (Serializable) which does not require much work from your side. The serialized information it produces contains the class name so the other side knows which class is responsible to create objects from the serialized data. Using that mechanism requires that both sides share the same classes (e.g. sharing a common library) and they must both be written in Java (* possible that there are ways around that). It's also a good idea if they have the exact same version of the class. Once you update just one side it may get difficult because that can change the way how state is expressed.

Other serialization mechanisms like JSON, Protocol Buffer, ... are typically independent of your concrete implementation and language. They still contain a description of all the required state but you are not bound to certain classes or even the concept of Objects.

2 Comments

Especially in the context of Netty, Does one vs. the other have any advantages (may be amount of data transfer!)? I already have Serializable java objects.
I don't know netty much but Protobuf is less data to transfer since it transfers binary data while JSON is text. Text requires multiple times the size of a binary. But you can GZIP compress text so it's not much more in the end. github.com/eishay/jvm-serializers/wiki compares some serialization mechansims and they all have advantages and disadvantages

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.