Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fundamentals of iostream and read/writeObject calls

I am designing a java server to respond to multiple client requests. So the design basically has a server socket, accepts a client socket, creates a inputObjectStream and a outputObjectStream from the client input/outputStream.

I then use writeobject on the client to make a request, readObject on the server to receive the request. Process it, write the object back on the same stream as a response, and on the client side readobject to process the response.

Now, if I run the code on a android emulator/device works fine. The same piece of code if I run on a "android junit java test case", i get a exception after it processes all my requests. The exception is on the server side on readObject call.

java.io.EOFException    at
java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2570)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1314)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368)`

Question Is it a correct design to read/writeObjects on a iostream ?

Edited

I have the sample project uploaded on 4shared.com (http://www.4shared.com/archive/98gET_pV/Issue15426tar.html) OR (http://www.sendspace.com/file/v04zjp)

Test 1 (PASS)

  1. TestServer project, run it as a Java Application
  2. TestClient project, run it as a Android Application

Console Output

Server Socket Opened /127.0.0.1

Client Socket Accepted

Input Stream created

Output Stream created

Read Object created

Test 2 (FAIL)

  1. TestServer project, run it as a Java Application
  2. TestClient project, run it as a Android Junit Test

Console Output

Server Socket Opened /127.0.0.1

Client Socket Accepted

Error : Unable to open server socket. Server wont load.
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2297)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2766)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:797)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:297)
at com.test.server.myThread.run(Main.java:52)
at com.test.server.Main.main(Main.java:32)
like image 737
Siddharth Avatar asked Oct 08 '11 05:10

Siddharth


1 Answers

Not sure if this causes this specific problem, but you should always use this order when creating object streams:

  1. Create ObjectOutputStream
  2. Flush it
  3. Create ObjectInputStream

I see that at least on the server side you created ObjectInputStream first and didn't flush the stream which might cause your problems.

Here is more info about the topic and reasons behind this order.

like image 139
Lycha Avatar answered Oct 13 '22 20:10

Lycha