How can I send multiple objects over one socket in java?

5.4k views Asked by At

When I send only one object through a socket i am ok. But when i am trying to send two objects, i get

Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source))

I have tried almost everything like flush() or reset() but none of them work.

public String SendObject(Object o) throws IOException {
    OutputStream outToServer = client.getOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(outToServer);
    out.writeUnshared(o);
    InputStream inFromServer = client.getInputStream();
    DataInputStream in = new DataInputStream(inFromServer);
    return in.readUTF();
}
3

There are 3 answers

3
Elliott Frisch On

You're using an ObjectOutputStream to write the Object(s) from the client. You should be using an ObjectInputStream (not a DataInputStream) to read them on the server. To read two Objects might look something like,

InputStream inFromServer = client.getInputStream();
ObjectInputStream in = new ObjectInputStream(inFromServer);
Object obj1 = in.readObject();
Object obj2 = in.readObject();

Also, on the client, I think you wanted writeObject (instead of writeUnshared) like

ObjectOutputStream out = new ObjectOutputStream(outToServer);
out.writeObject(o);
0
user207421 On
  1. You must use the same streams for the life of the socket, not new ones per send (or receive).
  2. You need to decide between Object streams and Data streams. Don't mix them.
  3. Don't try to mix between writeObject()/writeUnshared() and readUTF().
2
Stephen C On

While the other answers (e.g. @EJP's) are correct about the right way to send / receive objects and handle the streams, I think that the immediate problem is on the server side:

Exception in thread "main" java.net.SocketException: Connection reset

This seems to be saying that the connection has broken before the client receives a response. When the client side attempts to read, it sees the broken (reset) connection and throws the exception.

If (as you say) the sendObject method works first time, then I suspect that the server side is closing its output stream to "flush" the response ... or something like that.