How to transfer objects over a network using java

Which library should I use? What features help me?

+3
source share
4 answers

The easiest way is to use serialization . Thus, your object classes must implement serializable, so all members (primitives and most standard Java classes already do this). This allows matching between instances of objects and streams of bytes at runtime.

You also need a protocol for trance. You can watch RMI if you do not want to deal with streaming byte streams over a wire, although this is not difficult. However, using RMI allows you to create more powerful distributed Java applications later.

+8
source

ObjectOutputStream / ObjectInputStream.

All logic is approximately the following. Adjust the requirements of your application.

Send:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(objectToSend);
oos.close();

byte[] bytes = baos.toByteArray();
socket.write(bytes);

Reception:

ObjectInputStream ois = new ObjectInputStream(socketInputStream);
MyObject mo = (MyObject)ois.readObject();
+7
source

:

Java, Java . , Java Serialization, . Google "Java serialization gotchas".

Java , - , . " Google" "Apache Thrift" ( 1 ).

, XML .:)

Google , , - , , , Buffer.

+3

If you work in a multi-platform environment, you can use CORBA . Although this is a bit complicated because you may need to control both endpoints and implement interface definition interface (IDL) bindings.

A good alternative is to use JSON . You just need to map the JSON structure to your Java objects.

0
source

Source: https://habr.com/ru/post/1751903/


All Articles