创建一种通过网络发送整数的有效方法。 TCP

如何将整数值转换为字节数组,然后通过字节流将它们发送到客户端程序,该程序将字节数组转换回整数?

我的节目是乒乓球比赛。 一旦运行,它就会创建一个服务器,客户端现在使用对象流通过Internet连接到该服务器。 一切都运作良好,但似乎效率不高。 我的意思是球在试图通过更新循环保持同步时来回震动 。 我可能已经松散地编程了,但这是我能想到的最好的。 我希望有更多了解这种事情如何运作的人可以帮助我清除一些事情。

我的问题直截了当。 我需要知道更好的方式来更有效地在互联网上发送球位置和球员位置。 目前花费的时间太长了。 虽然,我可能会以错误的方式更新它。

流的构建方式:

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()进行传输。

这是我每次使用的function,它非常简单,工作完美,但function不需要(只是非常容易使用)

 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]);