0

So, I write an object to a client like so:

ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.writeObject(args);
out.close();

And receive the object on the client side like so:

ObjectInputStream in = new ObjectInputStream(connection.getInputStream());

Object objIn;
while(true) {
    if((objIn = in.readObject()) != null) {
        //work with obj
    }
}

I never create an output stream on the client side or an input stream on the server side.

Also, the object I send is serializable.

Thanks for you help!

EDIT: The "duplicate" of this question doesn't help me answer my problem, so this one is not a duplicate.

LAB
  • 85
  • 1
  • 1
  • 6

2 Answers2

0
while(true) {
    if((objIn = in.readObject()) != null) {
        //work with obj
    }
}

Q. Why are you testing for null? Are you planning on sending a null? Because that's the only time you'll ever get one. A. Because you think readObject() returns null at end of stream. Although you've left out the break that would escape the infinite loop.

It doesn't. It throws EOFException. So your loop should look like this:

try
{
    while(true) {
        objIn = in.readObject();
        //work with obj
    }
}
catch (EOFException exc)
{
    // end of stream
}
finally
{
    in.close();
}
user207421
  • 305,947
  • 44
  • 307
  • 483
-1

Assuming you received the exception while reading the input stream from connection Object .

If you already invoked the connection.getInputStream() prior to the above cited code for input stream you will receive a EOF exception . Because the input Stream in the connection object is already consumed .

related topic

One solution to such problem is to write the content of the input stream in a Random access file as they enables you to traverse through the file .

public static RandomAccessFile toRandomAccessFile(InputStream is, File tempFile) throws IOException
    {
        RandomAccessFile raf = new RandomAccessFile(tempFile, "rwd");
        byte[] buffer = new byte[2048];
        int    tmp    = 0;
        while ((tmp = is.read(buffer)) != -1)
        {
            raf.write(buffer, 0, tmp);
        }
        raf.seek(0);
        return raf;
    }

Later you can always read from the file as follows .

public static InputStream toInputStream(RandomAccessFile file) throws IOException
    {
        file.seek(0);    /// read from the start of the file 
        InputStream inputStream = Channels.newInputStream(file.getChannel());
        return inputStream;
    }
Community
  • 1
  • 1