Module concord_core

Class Serializer

java.lang.Object
nl.andrewl.concord_core.msg.Serializer

public class Serializer extends Object
This class is responsible for reading and writing messages from streams. It also defines the set of supported message types, and their associated byte identifiers, via the registerType(int, Class) method.
  • Field Details

    • messageTypes

      private final Map<Byte,MessageTypeSerializer<?>> messageTypes
      The mapping which defines each supported message type and the byte value used to identify it when reading and writing messages.
    • inverseMessageTypes

      private final Map<MessageTypeSerializer<?>,Byte> inverseMessageTypes
      An inverse of messageTypes which is used to look up a message's byte value when you know the class of the message.
  • Constructor Details

    • Serializer

      public Serializer()
      Constructs a new serializer instance, with a standard set of supported message types.
  • Method Details

    • registerType

      private <T extends Message> void registerType(int id, Class<T> messageClass)
      Helper method which registers a message type to be supported by the serializer, by adding it to the normal and inverse mappings.
      Parameters:
      id - The byte which will be used to identify messages of the given class. The value should from 0 to 127.
      messageClass - The type of message associated with the given id.
    • readMessage

      public Message readMessage(InputStream i) throws IOException
      Reads a message from the given input stream and returns it, or throws an exception if an error occurred while reading from the stream.
      Parameters:
      i - The input stream to read from.
      Returns:
      The message which was read.
      Throws:
      IOException - If an error occurs while reading, such as trying to read an unsupported message type, or if a message object could not be constructed for the incoming data.
    • writeMessage

      public <T extends Message> void writeMessage(Message msg, OutputStream o) throws IOException
      Writes a message to the given output stream.
      Parameters:
      msg - The message to write.
      o - The output stream to write to.
      Throws:
      IOException - If an error occurs while writing, or if the message to write is not supported by this serializer.