【发布时间】:2014-02-07 00:50:42
【问题描述】:
在客户端-服务器程序中,我有这个对象:
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);
}
}
【问题讨论】:
标签: java stream network-programming