Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ObjectInputStream hanging

I am feeling really stupid right now guys.... basically I am connecting over TCP on a local machine... and when I try to make the In/out streams at the client it wont get passed creating the object input stream. What gives? This stops after printing 2... no exceptions or anything... This isn't the first time I've used this class which is partialy why I am puzzled.

try {
            System.out.println("1");
            mySocket = new Socket("localhost", 11311);
            System.out.println("12");
            oos = new ObjectOutputStream(mySocket.getOutputStream());
            System.out.println("2");
            ois = new ObjectInputStream(mySocket.getInputStream());
            System.out.println("13");

        } catch (Exception e) {
            e.printStackTrace();
        }
like image 390
Michael Avatar asked Oct 01 '11 19:10

Michael


2 Answers

From the specification of ObjectInputStream:

This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.

like image 63
Kris Avatar answered Oct 16 '22 05:10

Kris


(For future readers:) I had the same problem because i made a silly change in server program and didn't test it for a long time then i was confused about why program is locked.

ServerSocket accepts the connection (responderSocket = serverSock.accept();) then suddenly for a inapropriate if (The silly change i mentioned!) program jumps out of the thread and because i didn't add a finally block to close streams and sockets the socket was left abandoned w/o sending or recieving anything (even stream headers). So in client side program there was no stream header (When i debbugged The code i saw that the last function executed before lock was:

public ObjectInputStream(InputStream in) throws IOException {
    verifySubclass();
    bin = new BlockDataInputStream(in);
    handles = new HandleTable(10);
    vlist = new ValidationList();
    enableOverride = false;
    readStreamHeader();                  //// <== This function
    bin.setBlockDataMode(true);
}

readStreamHeader();)

So be careful about what happens in server side, maybe problem isn't where you expecting it!

like image 33
Mohammad Jafar Mashhadi Avatar answered Oct 16 '22 05:10

Mohammad Jafar Mashhadi