0

所以我有一个服务器-客户端组合,它应该来回传递一个自定义对象。我使用 ObjectInputStream 和 ObjectOutpustStream 类来实现这一点。

这是服务器的循环:

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

它似乎一遍又一遍地接收相同的数据,但根据我的日志,客户端应该正在发送新数据。

有谁知道我做错了什么?

4

1 回答 1

2

发送一次对象后,它会发送对该对象的引用。这表示

  • 如果您改变一个对象并再次发送它,您将看不到更改
  • 对象流的内存将不断增长,因为它需要保留对已发送/接收的每个对象的引用。

避免这两个问题的方法是reset()定期打电话。图书馆无法为您执行此操作,因为它不知道可以安全地完成什么。

于 2012-10-20T09:32:45.613 回答