How can I convert integer values to byte arrays and then send them over a byte stream to the client program which converts the byte array back to an integer?
My program is a pingpong game. Once run it creates a server which a client connects to over the internet using an object stream right now. All is working well, but it doesn't seem very efficient. By that I mean the ball is stuttering back and forth while it is trying to keep in sync via the update loop. I may have programmed it loosely, but it was the best I could come up with. I hope someone who knows a lot more about how this kind of thing works can help me clear some things up.
My question put straight. I need to know a better way to send the ball positions and player position over the internet more efficiently. Currently the time it takes is too long. Although, I could be updating it the wrong way.
The way the streams are constructed:
oostream = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
oostream.flush();
oistream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
This is player 2's update loop:
IntData id = new IntData();
while (running) {
id.ballx = ballx;
id.bally = bally;
id.player2Y = player2Y;
oostream.writeObject(id);
oostream.flush();
Thread.sleep(updaterate);
id = (IntData) oistream.readObject();
player1Y = id.player1Y;
ballx = id.ballx;
bally = id.bally;
}
Player 1 is the server host. This is player 1's update loop:
IntData id = new IntData();
while (running) {
id = (IntData) oistream.readObject();
player2Y = id.player2Y;
ballx = id.ballx;
bally = id.bally;
Thread.sleep(updaterate);
id.ballx = ballx;
id.bally = bally;
id.player1Y = player1Y;
oostream.writeObject(id);
oostream.flush();
}
I suggest not using full serialization for simply primitives. use DataInputStream
and the like instead:
dostream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
distream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
Then read with:
ballx=distream.readInt();
bally=distream.readInt();
and write as:
dostream.writeInt(ballx);
dostream.writeInt(bally);
Also I suggest you not sleep awaiting data on both sides. Sleep on one and let the second simply await for a full set of data before transmitting by cutting out the Thread.sleep()
there.
this is the function im using everytime for it its pretty simple and works perfectly but the function is not rly needed (just very easy to use)
public static final byte[] parseIntToByteArray(int i){
byte[] b = {(byte)(i >> 24),
(byte)(i >> 16),
(byte)(i >> 8),
(byte)i};
return b;
}
to get it back:
int xy = (bytearray[0] << 24 | bytearray[1] << 16 | bytearray[2] << 8 | bytearray[3]);
来源:https://stackoverflow.com/questions/19351159/creating-an-efficient-way-of-sending-integers-over-a-network-tcp