Java序列化数据不匹配



我正在使用Java SE 7通过ServerSocket/Socket创建一个简单的聊天程序。我想知道是否有可能从客户端到服务器发送的模型/实体内的数据不匹配,反之亦然?当我发送具有不同包含数据的相同类类型时,我从客户端的发送模型到其服务器的数据不匹配。

Example
Client: Sending...  ID: 3
Server: Received... ID: 3
Client: Sending...  ID: 4
Server: Recieved... ID: 3

这里是我的模型/实体的通用范式:

abstract class Record<T> extends Observable implements Serializable {
   // with generated "serialVersionUID" by the EclipseIDE[Juno]
   protected int id;
   // Constructor, Getters/Setters, Abstract methods
   // hashCode(): Generated by Eclipse
   // equals(): Generated by Eclipse, replacing Record with Record<T>
}
abstract class RecordVersion<T> extends Record<T> implements Serializable {
   // with generated "serialVersionUID" by the EclipseIDE[Juno]
   protected int version;
   // Constructor, Getters/Setters, Abstract methods
   // hashCode(): Generated by Eclipse
   // equals(): Generated by Eclipse, replacing RecordVersion with RecordVersion<T>
}
class SampleRecord extends RecordVersion<SampleRecord> {
   // with generated "serialVersionUID" by the EclipseIDE[Juno]
   private String data;
   // Constructor, Getters/Setters, Abstracted methods
   // hashCode(): Generated by Eclipse
   // equals(): Generated by Eclipse
}

有什么办法解决这个问题吗?谢谢。

更新1:

通过java.io.ObjectInputStream读取socket.getInputStream()

class ReadRunnable implements Runnable {
  private Object lastObjectReceived = new Object();
  @Override
  public void run() {
    while(true) {
       try {
         // inStream: java.io.ObjectInputStream
         Object objectReceived = inStream.readObject();       
         if(objectReceived .equals(lastObjectReceived ))
           objectReceived = inStream.readObject();
         else
           lastObjectReceived = objectReceived;
       } catch(Exception e) {
         ex.printStackTrace();
       }
    }
  }
}

如果您试图通过相同的ObjectOutputStream多次发送相同的对象实例,您将遇到问题,因为对象流保留对象标识。为了用新数据重新发送相同的对象实例,您需要在两者之间调用ObjectOutputStream.reset()

同样,在你的循环中,你"丢失"了一个发送的对象。if块的第一个分支调用.readObject(),然后while循环的开始再次调用.readObject(),在比较之前丢弃前一个调用的结果。

相关内容

  • 没有找到相关文章

最新更新