I am creating a simple chat program using Java SE 7 via ServerSocket/Socket. I was wondering if it is possible to have a mismatch of data inside the sent model/entity from client to server or vise-versa? I am getting a mismatch of data from the sent model of my client to its server when I sent the same class type with different containing data consequently.
Example
Client: Sending... ID: 3
Server: Received... ID: 3
Client: Sending... ID: 4
Server: Recieved... ID: 3
Here my generic paradigm of my model/entity:
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
}
Any ideas how to solve this? Thanks.
UPDATE 1:
Reading the socket.getInputStream() via 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();
}
}
}
}
If you are attempting to send the same object instance multiple times over the same ObjectOutputStream, you are going to run into problems because Object streams preserve object identity. in order to resend the same object instance with new data, you need to call
ObjectOutputStream.reset()in between.Also, in your loop you are “losing” one of the objects sent. the first branch of your
ifblock calls.readObject(), and then the beginning of your while loop calls.readObject()again, discarding the result of the previous call before comparing it.