[英]Java: Writing the same object with new parameters in output stream several times
在客戶端服務器程序中,我有這個對象:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.