Hooli
Hooli

Reputation: 1195

socket closing early on multiple transfers

I'm trying to send an object over the network to another computer (or the same computer) and then have said computer send an object back.

On the sending computer, I send the object and receive the returned object:

ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        objectOutputStream.writeObject(object);
        Object returnedObject;
        socket.setSoTimeout(timeout);
        try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
            returnedObject = (Object) ois.readObject();
        }
        return returnedObject;

On the receiving computer, I receive the object:

Object object;
        socket.setSoTimeout(timeout);
        try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
            object = (Object) ois.readObject();
        }
        return object;

and then send an object back:

socket.setSoTimeout(timeout);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        objectOutputStream.writeObject(object);

The error I get back is:

SEVERE: null java.net.SocketException: Socket is closed at java.net.Socket.setSoTimeout(Socket.java:1137) at

and it occurs while attempting to send an object back on the receiving computer.

The socket on the sending computer is using the same address and port as the socket on the receiving computer.

Upvotes: 1

Views: 376

Answers (2)

RealSkeptic
RealSkeptic

Reputation: 34638

You are using a very small-scoped try-with-resources:

try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
    returnedObject = (Object) ois.readObject();
}

This code is interpreted as:

  • Get the input stream and build an ObjectInputStream around it.
  • Read an object from the object stream
  • Close the ObjectInputStream.

When you close the ObjectInputStream it automatically closes the InputStream that backs it, which is the socket's input stream. And the documentation of getInputStream says:

Closing the returned InputStream will close the associated socket.

You should make sure the try-with-resources has a bigger scope that covers the entire lifetime of the socket, or avoid using try-with-resources and make sure you close the ObjecInputStream properly when you are done with it or when there is an error.

Upvotes: 0

user207421
user207421

Reputation: 311018

This exception means that you closed the socket and then continued to use it. Specifically, you closed the ObjectInputStream at the end of the try-with-resources block where it is declared. That closes the other stream of the socket and the socket itself.

Don't use new object streams per transfer. Use the same ones for the life of the socket, at both ends.

Upvotes: 2

Related Questions