If the sender uses ois.writeObject
to continuously send two objects of the same class to the receiver, and the receiver uses oos.readObject
to read, is it possible for the receiver to treat the two data packets as one? And when the class to be serialized is very large, how does the receiver know when the reception is complete?
There is a way to point out that Object
can be used as boundary markers, but I don't know if it is correct
//sender
out.writeObject(obj1);
out.writeObject(new Object());
out.writeObject(obj1);
out.writeObject(new Object());
//receiver
Object obj;
while ((obj = in.readObject()) != null) {
if (obj instanceof Object) {
// Boundary identification, process the next object
} else {
// process the received object
}
}
but I am thinking about whether it is necessary to design an application layer protocol to allow the receiver to distinguish the boundaries of the message
Java Serialization does that for you. If Java Serialization didn't do this, it would be impossible to read more than one Object
from a ObjectInputStream
, since the boundary between the objects would be unspecified. If you're curious how Java Serialization does this, the Java Object Serialization Specification, in particular the Object Serialization Stream Protocol section, should prove instructive (very briefly: variable length data is prefixed with its length).
That said, using Java Serialization to interpret untrusted data is likely to result in serious security vulnerabilities. Most networked software is better served with more robust serialization formats, such as JSON or XML. There are open source libraries for both of these.
Alternatively, you could reinvent the wheel by using a naked DataOutputStream
/ DataInputStream
. For comparatively simple messages, this shouldn't be too onerous.