【问题标题】:Java: Writing the same object with new parameters in output stream several timesJava:在输出流中多次写入具有新参数的相同对象
【发布时间】: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


【解决方案1】:

没有看到您的客户端和服务器代码,我无法确定,但我怀疑问题在于您如何使用 ObjectOutputStream

This question is similar to yours with a good answer.

【讨论】:

  • 是的。这个问题和我的很相似,它的答案解决了我的问题!谢谢。
  • 没问题,很高兴为您提供帮助!
猜你喜欢
  • 2011-11-25
  • 1970-01-01
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多