整数值转换为字节数组,然后通过字节流将它们发送到将字节数组转换回整数的客户端程序?
我的程序是乒乓球游戏。运行后,它会创建一个服务器,客户端现在使用对象流通过互联网连接到该服务器。一切进展顺利,但似乎效率不高。我的意思是球在试图通过更新循环保持同步时来回卡顿。我可能编程得很松散,但这是我能想到的最好的。我希望对这种事情的工作原理有更多的了解的人可以帮助我澄清一些事情。
我的问题直截了当地问。我需要知道一种更好的方法来更有效地通过互联网发送球的位置和球员位置。目前花费的时间太长。虽然,我可能以错误的方式更新它。
流的构造方式:
oostream = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
oostream.flush();
oistream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
这是玩家 2 的更新循环:
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;
}
玩家 1 是服务器主机。这是玩家 1 的更新循环:
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();
}
我建议不要对简单的基元使用完全序列化。 请改用DataInputStream
等:
dostream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
distream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
然后阅读:
ballx=distream.readInt();
bally=distream.readInt();
并写成:
dostream.writeInt(ballx);
dostream.writeInt(bally);
另外,我建议您不要在等待双方的数据时睡觉。睡在一个上,让第二个简单地等待完整的数据集,然后通过切断那里的Thread.sleep()
进行传输。
IM每次使用它的函数它非常简单且运行完美,但不需要该功能(只是非常易于使用)
public static final byte[] parseIntToByteArray(int i){
byte[] b = {(byte)(i >> 24),
(byte)(i >> 16),
(byte)(i >> 8),
(byte)i};
return b;
}
要取回它:
int xy = (bytearray[0] << 24 | bytearray[1] << 16 | bytearray[2] << 8 | bytearray[3]);