From 80fc11f91e5a922b550ef9ed1ff340fb65cf0ded Mon Sep 17 00:00:00 2001 From: CyB3RC0nN0R Date: Mon, 6 Jan 2020 17:37:38 +0100 Subject: [PATCH] Fixed ObjectInputStream header error by reading chunks. --- .classpath | 6 ---- src/main/java/envoy/client/Receiver.java | 39 ++++++++++++++++-------- 2 files changed, 27 insertions(+), 18 deletions(-) diff --git a/.classpath b/.classpath index 1a0c560..a5d9509 100644 --- a/.classpath +++ b/.classpath @@ -28,11 +28,5 @@ - - - - - - diff --git a/src/main/java/envoy/client/Receiver.java b/src/main/java/envoy/client/Receiver.java index abe4687..e6cd3c5 100644 --- a/src/main/java/envoy/client/Receiver.java +++ b/src/main/java/envoy/client/Receiver.java @@ -1,5 +1,6 @@ package envoy.client; +import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.ObjectInputStream; import java.net.SocketException; @@ -10,12 +11,13 @@ import java.util.logging.Level; import java.util.logging.Logger; import envoy.client.util.EnvoyLog; +import envoy.util.SerializationUtils; /** * Project: envoy-client
* File: Receiver.java
* Created: 30.12.2019
- * + * * @author Kai S. K. Engelbart * @since Envoy v0.3-alpha */ @@ -36,29 +38,42 @@ 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(); } } /** * Adds an object processor to this {@link Receiver}. It will be called once an * object of the accepted class has been received. - * + * * @param processorClass the object class accepted by the processor * @param processor the object processor */