Question:

Send and receive objects through sockets with java?

by  |  earlier

0 LIKES UnLike

I'm using object input and output streams to send and receive objects through sockets. The client receives the first object, but when I send another objects it crashes (StreamCorruptedException). Does anyone know how to fix this?

I used global variables for the object input and output streams and the socket. The methods are pretty much the same on both sides of the socket(One sends MAC objects and receives MAS objects and the other sends MAS and receives MAC):

To initialize the streams:

private void getStreams() throws IOException

{

out=new ObjectOutputStream(new

BufferedOutputStream(

socket.getOutputStream()));

out.flush();

in=new ObjectInputStream(new

BufferedInputStream(

socket.getInputStream()));

}

To send an object:

public void send(Object obj){

try {

MAS m = new MAS(obj);

//MAS implements serializable

out.writeObject(m);

out.flush();

out.reset();

}catch ( IOException e) {

}

}

To receive an object:

private void receive() throws IOException

{

MAC m;

//MAC implements Serializable

do {

try {

m=(MAC)in.readObject();

m.setP(this);

m.chooseAction();

}catch ( ClassNotFoundException e) {

}

} while (true);

}

 Tags:

   Report

1 ANSWERS


  1. I think the culprit here is your call to out.reset().   This is being called before the other end has called/completed reading from the corresponding ObjectInputStream.  Just remove the reset() call and all should be good to go.

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.