Kahn Cse
Kahn Cse

Reputation: 437

ObjectOutputStream in Java

I have a function

public void loadUserOnline() {
        try {
            oos.writeObject(req); //Send request to Server to get online users
            oos.flush();
            LinkedList<UserOnlineInfo> userOnlineInfoList = (LinkedList<UserOnlineInfo>)ois.readObject(); // read object from Server contains online users
            Vector<String> listData = new Vector<>(); // a Vector for JList
            for (int i = 0; i < userOnlineInfoList.size(); i++) {
                listData.add(userOnlineInfoList.get(i).getUser() + " --- " + userOnlineInfoList.get(i).getStatus()); // add elements to Vector
            }
            theList.setListData(listData); // set data source for JList
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

The first time I call this function, it gets data from a server. Then data from the server changes. I call this function a second time, and the data is the same as the first time. Why?

Upvotes: 0

Views: 369

Answers (2)

user207421
user207421

Reputation: 310860

You need to call ObjectOutputStream.reset() every time you want to resend the same object with new values, or else use writeUnshared(). See the Javadoc.

Upvotes: 2

Noel M
Noel M

Reputation: 16116

You're using the same ObjectOutputStream instance, oos, which has been exhausted by the first call to this method. If you initialise your ObjectOutputStream again then you'll get a new stream:

public void loadUserOnline() {
   // initialise oos here or before the call to this method
   ObjectOutputStream oos = new ObjectOutputStream(...... 
   try {
      oos.writeObject(req);
....

Upvotes: 2

Related Questions