Java ObjectInputStream hanging

青春壹個敷衍的年華 提交于 2019-12-01 02:42:31

问题


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();
        }

回答1:


From the specification of ObjectInputStream:

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




回答2:


(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!



来源:https://stackoverflow.com/questions/7622396/java-objectinputstream-hanging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!