David K
David K

Reputation: 1346

StreamCorruptedException with heavy data over ObjectInputStream

I have a server-client setup over TCP where the client is sending a number of data sets to the server. The reading/writing uses ObjectInput/OutputStream. I don't have any problems under normal conditions, but when the data flow gets heavy, I get a StreamCorruptedException: invalid type code. The invalid code is different every time. I open the socket once and call a synchronized method to send data from multiple threads.

Client:

socket = new Socket("localhost", sockNum);
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());

public synchronized void sendMsg(Message msg){
    try{
        out.writeObject(security.signObject(msg, privKey));
        out.reset();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Server:

ServerSocket server = new ServerSocket(sockNum);
Socket client = server.accept();
ObjectInputStream in = new ObjectInputStream(client.getInputStream());

while(threadActive){
    Object line = in.readObject();
    handleObject(line);
}

Update: I added out.reset() after each send, but that didn't help the problem. I've also added sleep statments in my loop to decrease the data rate. This gets rid of the error but is not a real solution.

Edit: So it's been a little while since I originally asked this, but I'm running into the problem again. I tried setting up my system so that after every sent message, the thread waits for an "acknowledge" message in return. If the receiving process has the StreamCorruptedException, it sends back a "resend" rather than an ack. This seems to be causing more problems than solutions. Any other ideas?

Upvotes: 2

Views: 259

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533520

It sounds like you are writing to the output stream in a multi threaded way i.e. you are writing to it somewhere other than in your example.

BTW: Are you reset()ing the stream regularly to prevent a memory leak?

Upvotes: 2

Related Questions