0

I'am writing a simple copy of 'Space Invaders'. I want to add network feature, and atm I have problem with Writing/Reading data. So I have a LinkedList of (objects)Aliens and I want to send this to Client, to update thier positions.

The problem starts there:

On Server side I got exception: 'java.io.NotSerializableException: sun.awt.image.ToolkitImage'

(Class Alien implements Serializable)

On Client Side: 'StreamCorruptedException: invalid type code: AC'

Code where sending data to client:

else if(Server) 
{
    while(true)
    {
        ServerSocket server = new ServerSocket(1500);
        serverSocket = server.accept();
        new NetworkThreadHelp(serverSocket, board.GetAlienList()).start();
    } 
}

Code of NetworkThreadHelp:

public class NetworkThreadHelp extends Thread
{
    private Socket socket = null;
    private LinkedList<Alien> Aliens = new LinkedList<Alien>();

    public NetworkThreadHelp(Socket socket, LinkedList<Alien> A)
    {
        super("NetworkThreadHelp");
        this.socket = socket;
        this.Aliens = A;
    }

    public void run()
    {
        try
        {
            ObjectOutputStream objectOutput = new ObjectOutputStream(socket.getOutputStream());
            objectOutput.writeObject(Aliens);
            objectOutput.flush();
            objectOutput.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

Code where data is read:

else if(Client)
{
    Socket socket = new Socket("127.0.0.1",1500);
    ObjectInputStream objectInput;
    while (true) 
    {
        objectInput= new ObjectInputStream(socket.getInputStream());
        Object object = objectInput.readObject();//Here code doesn't initialize, everything below this won't execute
        LinkedList<Alien> Aliens = (LinkedList<Alien>) object;
        board.UpdateAliens(Aliens);
    }
}

My question is: how to make this work, write and read properly?

Warren Dew
  • 8,790
  • 3
  • 30
  • 44
VoidEye
  • 11
  • 5
  • The `NotSerializableException` is probably caused by serializing an inner class, which tries to take the containing class with it. The rest is a duplicate. – user207421 May 27 '15 at 00:48

1 Answers1

0

Most likely your Alien class contains an instance reference to an instance of the nonserializable ToolkitImage class. You may need to refactor your code so the Alien class doesn't contain such an instance reference, for exaample by making that reference a static constant. Alternatively, you can write custom writeObject(), readObject(), and readObjectNoData() methods for the Alien class as specified in the Javadoc for Serializable.

Your client side problem may or may not be a different problem, but I'd suggest fixing the server side problem first. If you still have a client side problem, you can always post another question.

Warren Dew
  • 8,790
  • 3
  • 30
  • 44