【问题标题】:Java SocketServer ObjectInputStream issue (wrong values are received) [duplicate]Java SocketServer ObjectInputStream 问题(接收到错误的值)[重复]
【发布时间】:2015-10-30 20:58:40
【问题描述】:

在过去的几个小时里我一直在调试,但我没有得到它....

我正在将一个对象从 Java Socket 服务器发送到客户端(游戏服务器和游戏客户端),并且在传递对象时似乎出现了问题......

服务器端:

//this is the controller function
public static void sendToAllPlayers(Object o){
    for (Connection c : NetworkService.getActiveConnections()){
        //i will explain this function below
        NetworkService.send(c, o);
    }
}

//this is the call to the controller
NetworkController.sendToAllPlayers(new SynchronizeMatch(MatchService.getMatchStore(), RoundService.getRoundStore()));

在 MatchStore (=> MatchService.getMatchStore()) 中列出了所有玩家。一个玩家看起来像:

class Player implements Serializable {
  private String username;
  private Integer points;
  ......
}

问题是,字段“points”没有从服务器正确传送到客户端。客户端:

Object object = in.readObject();
if (object instanceof SynchronizeMatch){
  SynchronizeMatch syncMatch = (SynchronizeMatch) object;
  MatchController.setMatchStore(syncMatch.getMatchStore);
  ......
}

到目前为止一切正常 - 比赛商店(以及回合商店)保留了游戏的所有“实时数据”,除了球员的得分水平。它没有正确更新。现在是 send() 函数:

public static void send(Connection c, Object o){
    try {
        c.getObjectOutputStream().writeObject(o);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我把答案贴在下面

【问题讨论】:

  • 您能否将其拆分为一个实际问题,然后发布您自己问题的答案。就目前而言,它可能会被关闭或投票否决,因为它目前的形式并不是一个真正的问题。
  • 哦,我一定会这样做

标签: java sockets object


【解决方案1】:

输入这个问题后,我找到了右边的解决方案:

public static void send(Connection c, Object o){
    try {
        c.getObjectOutputStream().writeObject(o);

        // !!!!!! THIS SOLVED MY PROBLEM !!!!!!

        c.getObjectOutputStream().reset();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

您需要重置 OutPutStream,否则它会缓存一些内容,并且您不知道您的所有数据集是否都是真实的。如果您想了解有关重置套接字连接的更多信息:

Is it ok to be calling reset() on an ObjectOutputStream very frequently?

我希望这会有所帮助;)

祝你今天愉快,

梅瑟比尔

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多