简体   繁体   中英

A problem with java Object Streams via sockets

I want to send an array of double as an object via ObjectOutputStream that uses a socket for outputStream. In the receiving side I read repetitious objects all the same! Maybe the assignment of method readObject doesn't perform it's task. I'm trying to update dobArray and write it to the socket output stream. dobArray is updated by another thread. It does it's task well, because I tested it. here is my code:

sending side:

    objectStream = new ObjectOutputStream(dataFlow.getOutputStream());

    while(busy){
        try {
            // dobArray is updated in another thread
            objectStream.writeObject( dobArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

receiving side:

    objectInputStream = new ObjectInputStream(
            mainServer.dataFlow.getInputStream());
    while (busy){
        try {
            DobArray dobarray =
                (DobArray) objectInputStream.readObject()
            writeToFile(dobarray);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

regards sajad

ObjectOutputStream is buffered. If you don't flush() the stream it can wait, buffered indefinitely.

When you pass a reference to an object it passes the value of that object only once. After that it only passes an object tag. This prevents recursive objects being serialized endlessly. However, if you pass a mutable object, on the first copy is sent.

Only way around this is to call reset(), but the simplest solution is to use writeUnshared() which sends the object every time.

while(busy)

You are in a loop, repeatedly sending this data? Why is this here and when is busy set to false?

You should only call writeObject one time.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM