2013-10-13 40 views
2

如何將整數值轉換爲字節數組,然後通過字節流將它們發送到將字節數組轉換回整數的客戶機程序?創建通過網絡發送整數的有效方法。 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(); 

      } 
+0

嘗試刪除睡覺。 'oostream'仍然會等待一個完整的對象。 – hexafraction

回答

5

我建議不要使用全系列化的根本原語。使用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()

+0

哦,這是正確的等待。這個人會等着閱讀,謝謝。 –

+1

+1在構建完成後,您不需要flush()。沒有什麼可以沖洗的。在兩端都不需要睡眠:read()將在接收方處阻塞,而flush()將在發送方處發送。 – EJP

+0

謝謝。爲了模擬目的,睡眠僅用於在我自己的計算機上進行測試。 –

0

這是利用每次函數IM它 其很簡單和完美的作品,但不RLY所需要的功能(只是非常好用)

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

這不起作用。它簽名擴展負字節。需要更多。但它已由DataInput和DataOutput提供。 – EJP

+0

可以使用>>>而不是>>來防止符號擴展。或者一個ByteBuffer。 – jmiserez

+0

否符號擴展在重建過程中發生。 >>>沒有幫助。在「-65408」上試試 – EJP