Object Stream Question / Problem

I am currently writing some software which uses ObjectInput/ObjectOutputStream to pass messages back and forth.

I have a class called Message, and a class called GameState, both are serializable

Inside Message, there is a GameState object, which holds the state of a current game.

I construct a GameState, then pass it into the constructor of Message, and set my pointer to point to that GameState.

I then try to send Message across an ObjectOutputStream to the client from the server.

Here is where a problem starts… I try to set up the stream in a thread on the client side with the following code:

	public ClientThread(Socket conn, GameClient gcl) {
		
		connection = conn;
		gc = gcl;
		
		try {
			out = new ObjectOutputStream(connection.getOutputStream());
	(36)		in = new ObjectInputStream(connection.getInputStream());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Which produces the following error:

java.io.StreamCorruptedException: invalid stream header
	at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
	at java.io.ObjectInputStream.<init>(Unknown Source)
	at Client.ClientThread.<init>(ClientThread.java:36)

My two questions are this:

  1. Can you pass an object through an OOS which contains a reference to another object, and retrieve both on the other side, for example:

GameState g = new GameState(args);
Message m = new Message(g); // this will simply contain a link to g in a private variable

OOS.writeObject(m);

then on the client:

Message m1 = (Message)(OIS.readObject());
GameState g1 = m1.getGameState();

Or does that fail completely somehow?

  1. What could be causing that error? I have never encountered it before and dont know where to turn at all…

See this thread: http://www.java-gaming.org/forums/index.php?topic=14035.0

For the exception, my guess is that you’re doing multiple writes with the one ObjectOutputStream but reading it with different ObjectInputStreams, or vice versa.

The other thing that can cause that error is when the bytes made by ObjectOutputStream sent over the network don’t come out the same on the other side. Or you a writing to the one ObjectOutputStream (or sending using the one Socket) with overlapping threads which causes the bytes to get muddled up.

Post some code if this hasn’t helped.
Keith