Patrick
Patrick

Reputation: 612

Java-Sockets: How to send and serialize object between multiple applications

I have 2 maven applications that should communicate via server socket and socket. If possible, I want to send the data as a Java-object, but for that I need both of those projects to include the class of the object.

If possible, I don't want to make a third maven project with the class and add it to the server and client project as a dependency. Is there any other way to do that?

Thanks for your answers!

Upvotes: 0

Views: 513

Answers (1)

cameron1024
cameron1024

Reputation: 10146

You could make your server project a sub-project of your client project, meaning that your server has access to all the classes the client needs, plus some extras.

Alternatively, you can create a JAR containing shared classes, and install this to your local (or remote if you have access) maven repository, using mvn install (docs here: https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html)

For the actual transfer of data, you could serialize your objects using the Serializable interface, however there are many issues with this approach:

  • Fragile to class changes - if you change your class, old objects will likely break unless you manually manage this
  • Java-only - you will not be able to, for example, write your client in C++ and your server in Java, if you ever decide to do something similar.
  • Framework incompatibility - many popular frameworks work primarily with other formats, and cannot guarantee compatibility.

Instead, you can use:

  • JSONs - Using Jackson Databind, or Google Gson libraries, they are flexible, powerful and standardised
  • XML - Similar to JSONs, with some subtle differences
  • Google Protobuf - Also has some limitations but very underrated for resource-constrained environments.
  • Custom String Format - implement your own toDataString() and fromDataString() methods. This is only really feasible for small classes, as there are many issues with Unicode, escape characters, encodings etc that most libraries hide from you. This is more risky than other methods.

In general, I would reccomend JSON unless you have a good reason to do otherwise. I personally use Jackson, here is a link to a tutorial: http://tutorials.jenkov.com/java-json/jackson-objectmapper.html

Upvotes: 1

Related Questions