如何將整數值轉換爲字節數組,然後通過字節流將它們發送到將字節數組轉換回整數的客戶機程序?創建通過網絡發送整數的有效方法。 TCP
我的程序是一個乒乓球遊戲。一旦運行,它將創建一個客戶端通過互聯網使用對象流現在連接到的服務器。所有工作都很好,但效果不是很好。我的意思是,當球試圖通過更新循環保持同步時,球會來回走動。我可能對它進行了鬆散編程,但這是我能想到的最好的。我希望有更多瞭解這種事情的人能幫助我清楚一些事情。
我的問題直接提出。我需要知道一個更好的方式來更高效地將球位置和球員位置傳送到互聯網。目前所花費的時間太長。雖然,我可能會錯誤地更新它。
流構造方式:
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();
}
嘗試刪除睡覺。 'oostream'仍然會等待一個完整的對象。 – hexafraction