diff --git a/main/src/main/java/sd/util/MessageSerializer.java b/main/src/main/java/sd/util/MessageSerializer.java new file mode 100644 index 0000000..2e7f461 --- /dev/null +++ b/main/src/main/java/sd/util/MessageSerializer.java @@ -0,0 +1,62 @@ +package sd.util; // Or sd.util if you prefer + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import sd.protocol.MessageProtocol; + +/** + * Utility class for serializing and deserializing MessageProtocol objects. + * * NOTE: The SocketConnection class already handles serialization/deserialization + * automatically via ObjectOutputStream and ObjectInputStream directly + * on the socket stream. This class serves more as an example or for + * scenarios where you might want to manipulate the bytes directly + * (e.g., for sending via UDP or other means). + */ +public class MessageSerializer { + + /** + * Serializes a MessageProtocol object into a byte array. + * * @param message The MessageProtocol object to be serialized. + * @return A byte array representing the serialized object. + * @throws IOException If an error occurs during serialization. + */ + public static byte[] serialize(MessageProtocol message) throws IOException { + // Use a ByteArrayOutputStream to write bytes into memory + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + + // Use an ObjectOutputStream to write the object into the byteStream + try (ObjectOutputStream objectStream = new ObjectOutputStream(byteStream)) { + objectStream.writeObject(message); + } // The try-with-resources automatically closes the objectStream + + // Return the resulting bytes + return byteStream.toByteArray(); + } + + /** + * Deserializes a byte array back into a MessageProtocol object. + * * @param data The byte array to be deserialized. + * @return The reconstructed MessageProtocol object. + * @throws IOException If an error occurs while reading the bytes. + * @throws ClassNotFoundException If the class of the serialized object cannot be found. + */ + public static MessageProtocol deserialize(byte[] data) throws IOException, ClassNotFoundException { + // Use a ByteArrayInputStream to read from the byte array + ByteArrayInputStream byteStream = new ByteArrayInputStream(data); + + // Use an ObjectInputStream to read the object from the byteStream + try (ObjectInputStream objectStream = new ObjectInputStream(byteStream)) { + // Read the object and cast it to MessageProtocol + return (MessageProtocol) objectStream.readObject(); + } // The try-with-resources automatically closes the objectStream + } + + // Private constructor to prevent instantiation of the utility class + private MessageSerializer() { + throw new UnsupportedOperationException("This is a utility class and cannot be instantiated."); + } +} \ No newline at end of file