Hi,
With Java Sockets you send and receive messages through the InputStream and OutputStream classes. The most basic tutorial reads lines of strings from these streams (as in a chat application or something).
What if you would like to send a bunch of primitive data types? One would think that wrapping the Streams into a DataInputStream and DataOutputStream would work - but here’s a problem. Each time you write to these streams the message is sent directly! You can’t bunch up a, say, 1 Byte and 2 Integers and a String ( in that order ) and then send the ‘package’ as whole through the Sockets Streams.
What I’ve been accustomed to from another language, is that you build a ‘package’ first, and then send the package - like this f.ex:
clearbuffer();
writeByte(1); // Used to identify what sort of message this is
writeInt(x);
writeInt(y);
writeString("Teddybears");
sendMessage(socket.outputStream);
This package would be extremely light as it would only be the size of the bytes that is sent.
In Java, I’ve noticed people sending whole Objects through Serialization. Which, to me, seems highly unnecessary - and a lot more heavy in size f.ex:
class PositionMessage() implements Serializable {
int x;
int y;
String msg;
}
...
PositionMessage msg = new PositionMessage();
msg.x = x;
msg.y = y;
msg.msg = "Teddybears";
// code to serialize the msg ( turn it into bytes )
sendMessage(socket.outputStream);
and to identify what kind of message is sent you use the ‘instanceof’ keyword, and for each different type of message you create a new class.
I would think that this Java solution, while it might work, creates a lot more unnecessary weight in my packets and that there should exist a more controlled way, like the former solution, in Java. Is there?