Search code examples
javasocketsobjectinputstreamobjectoutputstream

Error in receiving ObjectInputStream


I am trying to create a client server program where I'm sending an object from client and receiving the object at the server continuously in the while loop.

Client code:

ObjectOutputStream oos = null;
while(true){

            WorkerMessageToMaster message = new WorkerMessageToMaster(WorkerTasksStatus.getTaskStatusMap(), WorkerTasksStatus.getTaskStatusReduce());
            oos = new ObjectOutputStream(taskManagerSocket.getOutputStream());
            oos.writeObject(message);
            oos.flush();
            Thread.sleep(1000);
        }

Server code:

ObjectInputStream ois = null;
while (true ) {

            ois = new ObjectInputStream(clientSocket.getInputStream());
            WorkerMessageToMaster taskMapObject = (WorkerMessageToMaster)ois.readObject();
            System.out.println("Connection from: "+clientSocket.getInetAddress().getHostAddress().toString());

        }

When I try to run this code on my local system It runs normally, but when I try to run the client and server in different machines(different Ips) I get the following error.

java.io.StreamCorruptedException: invalid stream header: 74000432
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at master.MasterAnalyzer.heartBeat(MasterAnalyzer.java:58)
at master.MasterAnalyzer.run(MasterAnalyzer.java:80)
at java.lang.Thread.run(Thread.java:745)

I am confused at this erratic behavior as Im sending the stream through the client socket established with the server in a while loop and receiving it on the same socket connection accepted at the server and It seems to be working fine on local host.

Thank you for your help


Solution

  • You create a new stream for each object. Only create one output and one input stream. Object streams send header data which is maybe corrupted when you create a new stream.