So I have a client/server application and I'm trying to send an ArrayList of objects to the server. I kept getting errors sending the ArrayList of objects, so I just decided to send an empty ArrayList to see if anything was wrong, and it turns out, that the server can't read a regular ArrayList either. I don't think that this should happen because ArrayList is supposed to be Serializable, but maybe I'm wrong.


Server:

public void run(){
         while(true){     
            try{
               in = new ObjectInputStream(client.getInputStream());

               Object ob = in.readObject();

               ArrayList ca = new ArrayList();
               if(ob.getClass()==ca.getClass()){
                  System.out.println("yes");
               }

               if(ob.getClass()==focusBlock.getClass()){
                  focusBlock = (cblock) ob;
               }
            }
            catch(Exception e){e.printStackTrace();}
      
         }
}

Client:

synchronized void send(Object ob){
         try{
            out.writeUnshared(ob);
            out.flush();
         }
         catch(Exception e){e.printStackTrace();}
      }
     synchronized public void run(){
         while(true){
            try{
               out = new ObjectOutputStream(socket.getOutputStream());
               ArrayList comp = new ArrayList();

               send(game.getFocusBlock());
               send(comp.toArray());

            }
            catch(Exception e){}
        }

When I send my focusBlock object, everything is fine, but sending the ArrayList gives me this error:

java.io.StreamCorruptedException: invalid stream header
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:764)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:277)
at Server$observer.run(Server.java:69)
at java.lang.Thread.run(Thread.java:613)


Any help would be appreciated.

There's too much missing code to tell - but it looks like you may be reading the two objects in two separate threads each of which opens the inputstream? If so, try reading both objects together, just like they were written. I can confirm that ArrayLists of Objects transfer via writeObject/readObject just fine (provided the contents are serialisable).
Why are you using writeUnshared rather than a normal writeObject?

Thanks, that did it. I just needed to read the two objects in the same thread. I was using the writeUnshared method just to test to see if that would help the problem and ended up leaving it in when the problem wasn't solved. Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.