在客户端服务程序中,我有此对象:
class MyTestingObject implements Serializable {
int number;
void updateParams() {
number++;
}
@Override
public String toString() {
return String.format("has value %03d", number);
}
}
服务器是MyTestingObject
的新实例,但是在无限环路中,它调用updateParams()
,将其打印并将其发送给客户端(使用ObjectOutputStream
)。客户端也具有无限循环,其中打印了收到的对象(使用ObjectInputStream
)。
我期望的是:
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"
但是我得到的是:
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"
为什么会发生这种情况,更重要的问题我应该如何更改它以使其正如我期望的?
如果它有助于测试器代码是:(我知道它不是干净的,并且不是以最佳方式写的):
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);
}
}
我不确定您的客户端和服务器代码,但我怀疑问题是您如何使用ObjectOutputStream
。
这个问题与您的答案相似。