Frage

I am developing an client server application that will be communicating using UDP and packets.

I will be encoding a decoding data from these packets using DataOutputStream and DataInputStream.

The way i would like to store my data is inside a custom packet class extended from another custom base packet class.

This packet base class contains a list of objects, the packet data, (these objects will be in multiple formats; String, Int, Boolean...) and will be encoded to a DataOuputStream using the following method:

public ByteArrayOutputStream getDataOS(){
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    DataOutputStream os = new DataOutputStream(data);

    try {
        for(Object obj : packetData){
            if(obj instanceof String)
                os.writeUTF((String) obj);
            else if(obj instanceof Integer)
                os.writeInt((int) obj);
            else if(obj instanceof Byte)
                os.writeByte((Byte) obj);
            else if(obj instanceof Double)
                os.writeDouble((double) obj);
            else if(obj instanceof Boolean)
                os.writeBoolean((Boolean) obj);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } 

    return data;
}

This ByteArrayOutputStream will then be sent off to my packet handler and forwarded on to the client/server.

The road block i have run into is regarding how to read this packets DataInputStream on the other end.

As i will not be knowing what format each of the objects will be, i will not be able to read them using is.readUTF(); for example.

One method i have thought to combat this would be to send a byte object type identifier before each sent object. I.e int would be 0, UTF would be 1 and so on. This would allow me to prepare for each object read by using a case statement on the byte type identifier.

This will obviously add more data to my packets, which is not optimal. The reason i want to do it like this however is to avoid hard-coding each data read for each, possibly hundreds of packets.

What my question really is, is if this is a sensible way of going about this? Or is there an easier way of sending through custom structured packets, and reading them on the other side not necessarily knowing the data format..?

War es hilfreich?

Lösung

Obviously you have to write a token ahead of each item announcing what type it is.

Or use an ObjectOutputStream and just write and read objects, and use instanceof at the *receiving * end.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top