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"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </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"/> <classpathentry kind="output" path="target/classes"/>
</classpath> </classpath>

View File

@ -1,5 +1,6 @@
package envoy.client; package envoy.client;
import java.io.ByteArrayInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.net.SocketException; import java.net.SocketException;
@ -10,6 +11,7 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import envoy.client.util.EnvoyLog; import envoy.client.util.EnvoyLog;
import envoy.util.SerializationUtils;
/** /**
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
@ -36,8 +38,19 @@ public class Receiver implements Runnable {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public void run() { public void run() {
try (ObjectInputStream oin = new ObjectInputStream(in)) {
try {
while (true) { 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(); Object obj = oin.readObject();
logger.finest("Received object " + obj); logger.finest("Received object " + obj);
@ -48,10 +61,12 @@ public class Receiver implements Runnable {
logger.severe(String.format("The received object has the class %s for which no processor is defined.", obj.getClass())); logger.severe(String.format("The received object has the class %s for which no processor is defined.", obj.getClass()));
else processor.accept(obj); else processor.accept(obj);
} }
}
} catch (SocketException e) { } catch (SocketException e) {
logger.info("Connection probably closed by client. Exiting receiver thread..."); logger.info("Connection probably closed by client. Exiting receiver thread...");
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.SEVERE, "Error on receiver thread", e); logger.log(Level.SEVERE, "Error on receiver thread", e);
e.printStackTrace();
} }
} }