In a client-server program I have this object:
class MyTestingObject implements Serializable {
int number;
void updateParams() {
number++;
}
@Override
public String toString() {
return String.format("has value %03d", number);
}
}
Server makes a new instance of MyTestingObject
one time but in an infinite loop it calls updateParams()
, prints it and sends it to client (Using ObjectOutputStream
). Client has an infinite loop too which prints received object(Using ObjectInputStream
).
What i expect is :
server:
Sent "has value 1"
Sent "has value 2"
Sent "has value 3"
Sent "has value 4"
client:
Got "has value 1"
Got "has value 2"
Got "has value 3"
Got "has value 4"
But what i get is:
server:
Sent "has value 1"
Sent "has value 2"
Sent "has value 3"
Sent "has value 4"
client:
Got "has value 1"
Got "has value 1"
Got "has value 1"
Got "has value 1"
Why this happens and more important question how should i change it to make it work as i expect?
If it helps tester code is: (I know it's not clean and is not written in best way):
public static void main(String[] args) {
(new Thread() {
MyTestingObject serverInstance = new MyTestingObject();
{
serverInstance.number = 0;
}
@Override
public void run() {
try {
ServerSocket ss = new ServerSocket(8775);
Socket s = ss.accept();
Client cl = new Client();
cl.setSocket(s);
while (true) {
serverInstance.updateParams();
cl.sendObject(serverInstance);
System.out.printf("Sent \"%s\"\n", serverInstance);
}
} catch (IOException ex) {
Logger.getLogger(NetworkSendSameObjectWithNewValuesSeveralTimes.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
try {
Client cl = new Client("127.0.0.1", 8775);
cl.connect();
while (true) {
try {
System.out.printf("Got \"%s\"\n", cl.readObject());
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(NetworkSendSameObjectWithNewValuesSeveralTimes.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (IOException ex) {
Logger.getLogger(NetworkSendSameObjectWithNewValuesSeveralTimes.class.getName()).log(Level.SEVERE, null, ex);
}
}
Without seeing your Client and Server code I can't be sure, but I suspect the problem is with how you use ObjectOutputStream
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.