DataInput and Dataoutput Stream (approach for I/O)

Hello,

I am currently working on a networked game. I was sending positions and that kind of stuff like this:

//out and in are DataOuput and DataInput Streams

out.writeInt(x);
out.writeInt(y);

and receiving it:

in.readInt(x);
in.readInt(y);

I then thought that it was a better practice to send x and y in a single outputstream like this (Thought it will generate less traffic if I send data once and not twice):

out.writeUTF(x@y);

Then I will receive the data like this:

String data[] = in.readUTF.split("@");
x = Integer.parseInt(data[0]);
y = Integer.parseInt(data[1]);

I want to know if this is truly a good approach, is it faster than the one aforementioned. Or is there any other better approach or any suggestion. Thanks,

Elías

String.split(…) is a regex split. It’s a lot more predictable when you use indexOf + substring

I don’t think you will generate more packages when calling the the write methods for the single values, so stay with writeInt(). With writeUTF you will most likely generate more data (due to string encoded numbers) and have a processing overhead to parse the values out of the string. So no, I don’t think it is agood approach.

Thanks,

Someone tolde me to do this: Use a BufferedOutputStream between the DataOutputStream and the socket’s output stream, and only flush() the DataOutputStream when you’ve sent all the data for a particular transaction.

What´s your opinion on this option?

The socket’s OutputStream itself has a buffer (see: nagles algorithm). The cost to write to that buffer is rather high, so it’s preferable to insert a Buffered…Stream between the socket and the Data…Streams.

Thanks!!! :wink: