James Raitsev
James Raitsev

Reputation: 96381

Client server communication trouble

I am having trouble bouncing object between the client and the server.

Create an object. Update some fields. Send to Server. (this part works)

SomeObject thisObject = new SomeObject();
thisObject.setSomeValue(13);          // update object to be sent

PrintStream toServer = new PrintStream(sock.getOutputStream());

ObjectOutputStream oos = new ObjectOutputStream(toServer);

oos.writeObject(thisObject);
oos.close();

toServer.println(oos);               // send object to server
toServer.flush();

Right after this, server further updates some value and sets it to 1919;

ObjectInputStream objFromClient = new ObjectInputStream(new BufferedInputStream(
        sock.getInputStream()));

Served thisObject = (Served) objFromClient.readObject();
thisObject.setSomeValue(1919);

Server then sends the object back to client

toClient = new PrintStream(sock.getOutputStream());
ObjectOutputStream oos = new ObjectOutputStream(toClient);

oos.writeObject(thisObject);

oos.close();
objFromClient.close();
sock.close();

But when the time comes to pick up the object back on the client side .. programs fails with Socket Closed exception

ObjectInputStream objFromServer = new ObjectInputStream(
    new BufferedInputStream(sock.getInputStream()));      //java.net.SocketException: Socket is closed

thisObject = (Served) objFromServer.readObject();
....

Please help me understand the issue

Upvotes: 0

Views: 99

Answers (1)

Paul Bellora
Paul Bellora

Reputation: 55213

My guess is you're using the same Socket to both send and receive from the client. When you close the ObjectOutputStream on the client, this closes the underlying OutputStream, which closes sock. Then, when you try to reuse it below, it's been closed and throws an exception.

Instead, wait for the transaction to finish before closing your resources in the client code (which should be done in a finally block by the way). Or, if waiting is problematic, use a new Socket instead.

Upvotes: 2

Related Questions