Fixed ObjectInputStream header error by reading chunks.

This commit is contained in:
Kai S. K. Engelbart 2020-01-06 17:37:38 +01:00
parent d005bcd4c9
commit 80fc11f91e
2 changed files with 27 additions and 18 deletions

View File

@ -28,11 +28,5 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@ -1,5 +1,6 @@
package envoy.client;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.SocketException;
@ -10,6 +11,7 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import envoy.client.util.EnvoyLog;
import envoy.util.SerializationUtils;
/**
* Project: <strong>envoy-client</strong><br>
@ -36,22 +38,35 @@ public class Receiver implements Runnable {
@SuppressWarnings("unchecked")
@Override
public void run() {
try (ObjectInputStream oin = new ObjectInputStream(in)) {
while (true) {
Object obj = oin.readObject();
logger.finest("Received object " + obj);
// Get appropriate processor
@SuppressWarnings("rawtypes")
Consumer processor = processors.get(obj.getClass());
if (processor == null)
logger.severe(String.format("The received object has the class %s for which no processor is defined.", obj.getClass()));
else processor.accept(obj);
try {
while (true) {
// Read object length
byte[] lenBytes = new byte[4];
in.read(lenBytes);
int len = SerializationUtils.bytesToInt(lenBytes, 0);
// Read object into byte array
byte[] objBytes = new byte[len];
in.read(objBytes);
try (ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(objBytes))) {
Object obj = oin.readObject();
logger.finest("Received object " + obj);
// Get appropriate processor
@SuppressWarnings("rawtypes")
Consumer processor = processors.get(obj.getClass());
if (processor == null)
logger.severe(String.format("The received object has the class %s for which no processor is defined.", obj.getClass()));
else processor.accept(obj);
}
}
} catch (SocketException e) {
logger.info("Connection probably closed by client. Exiting receiver thread...");
} catch (Exception e) {
logger.log(Level.SEVERE, "Error on receiver thread", e);
e.printStackTrace();
}
}