Search code examples
javasocketsserializationobjectinputstream

Writing into an ObjectInputStream repeatedly


I have multiple clients and one server. Server handles each client in one thread. Clients must send a custon object to the master. I checked this and this, which talk about the error java.io.StreamCorruptedException: invalid type code: AC which is exactly I'm having.

But I didn't understood the proposed solution. He inherits the ObjectOutputStream and simple does not write the header in the second and following times the object must be sent. This is not working for me.

Is there another solution to send custom objects throught TCP sockets? My clients gather their data every 10 seconds and re-created the object which is sent.

I'm sorry if i'm being repetitive, I'm reading a lot of similar question but finding no answers to my scenario.

Thanks in advance

EDIT

Send method (in the client)

    public void TCPEchoClientSend(MonitoredData _mData) throws IOException {
        if (_mData == null)
            throw new IllegalArgumentException("Parameter: <Monitored Data> empty.");           
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

        // Send the encoded object to the server
        oos.writeObject(_mData);

        oos.close();

        System.out.println("Client sent the monitored data package.");

    }

Receive

public static void handleEchoClient(Socket client, Logger logger) {
        try {
            MonitoredData mdata;
            // Get the input and output I/O streams from socket
            ObjectInputStream ois = new ObjectInputStream(client
                    .getInputStream());
            ObjectOutputStream oos = new ObjectOutputStream(client
                    .getOutputStream());

            // Receive until client closes connection, indicated by -1;
            while ((mdata = (MonitoredData) ois.readObject()) != null) {

                System.out.println("Got received data. Ready to save.");

                hdb.saveOrUpdate(mdata);

                System.out.println("Monitored Data arrived at home.");

            }

            // logger.info("Client " + _clntSock.getRemoteSocketAddress()+
            // ", echoed " + totalBytesEchoed + " bytes.");

        } catch (IOException ex) {
            logger.log(Level.WARNING, "Exception in echo protocol", ex);
        } catch (ClassNotFoundException e) {
            logger.log(Level.WARNING, "Exception in echo protocol", e);
        } finally {
            try {
                client.close();
            } catch (IOException e) {
            }
        }
    }

Solution

  • Use the same ObjectOutputStream and ObjectInputStream for the life of the socket, at both ends, and look up the ObjectOutputStream reset() and writeUnshared() methods.

    See this answer for a discussion.