1

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

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:

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

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();
       }
    }
  }
}
4

1 回答 1

2

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

Also, in your loop you are "losing" one of the objects sent. the first branch of your if block calls .readObject(), and then the beginning of your while loop calls .readObject() again, discarding the result of the previous call before comparing it.

于 2012-12-20T18:17:32.607 回答