0
所以我有一個服務器 - 客戶端組合,它只是應該來回傳遞一個自定義對象。我'使用ObjectInputStream和ObjectOutpustStream類來實現這一點。Java服務器一遍又一遍地接收相同的數據
這裏是服務器的循環:
while((inputPosition = (Vector2i) objectIn.readObject()) != null) {
Print.log("input line: " + inputPosition.toString());
outputLine = "you moved to " + inputPosition.toString();
out.println(outputLine);
}
凡inputPosition是Vector2i,一個簡單的類,只是擁有2個整數,x和y。
這裏是客戶端的循環:
while((serverOutput = in.readLine()) != null) {
Print.log("Server says: " + serverOutput);
position = calculatePosition(position, reader);
Print.log("sending over: " + position.toString());
objectOut.writeObject(position);
}
的計算位置的方法看起來就像這樣:
private static Vector2i calculatePosition(Vector2i position, BufferedReader reader) throws IOException {
Print.log("i just got this: " + position.toString());
String entry = reader.readLine().substring(0, 1);
if(entry.equals("w"))
position.y++;
else if(entry.equals("s"))
position.y--;
else if(entry.equals("a"))
position.x--;
else if(entry.equals("d"))
position.x++;
return position;
}
因此,這裏發生了什麼。我連接到服務器和移動一個成功的座標後,它剛剛獲得的卡在同一座標一遍又一遍:
Server says: Use wasd to move around.
i just got this: 5, 5
w
sending over: 5, 6
Server says: you moved to 5, 6
i just got this: 5, 6
w
sending over: 5, 7
Server says: you moved to 5, 6
i just got this: 5, 7
a
sending over: 4, 7
Server says: you moved to 5, 6
i just got this: 4, 7
您可以在「送過」行看到,在客戶端的vector2i對象是最新的,但我從服務器得到的迴應是一次又一次。有服務器的日誌是這樣的:
input line: 5, 6
input line: 5, 6
input line: 5, 6
這似乎是一遍又一遍地接受相同的數據,但根據我的日誌,客戶應該可以在發送新數據。
有沒有人有一個想法我做錯了什麼?
哦,是啊...只需在循環結尾添加objectOut.reset()即可解決問題。謝謝! – JMRboosties