问题
I have tried every solution I can find to this problem.
server = new ServerSocket(9421);
client = new Socket("localhost", 9421);
out = new ObjectOutputStream(client.getOutputStream());
out.flush();
System.out.println("Starting input streams");
in = new ObjectInputStream(client.getInputStream());
System.out.println("input streams are now running");
Everything tells me to declare the objectInputStream before the ObjectInputStream. Other places tell me to flush the Object output stream. This code just hangs the program and waits waiting for the so-called header.
回答1:
Everything tells me to declare the objectInputStream before the ObjectInputStream.
No it doesn't, it tells you to construct the ObjectOutputStream
before the ObjectInputStream
, and you're doing that.
Other places tell me to flush the Object input stream.
No, they tell you to flush the ObjectOutputStream
, and you're doing that too.
Do read accurately.
This code just hangs the program and waits waiting for the so-called header.
That is exactly 100% correct. There is nothing 'so-called' about it. And nothing has written the header. The peer hasn't constructed its ObjectOutputStream
yet, and this code will block until it does, or disconnects, or the network drops out.
In fact the peer hasn't even accepted the connection. You can't run all this code in the same thread. The ServerSocket
needs a separate accept-loop thread, and that thread needs to start a further thread per accepted socket that constructs the object streams in the same order.
来源:https://stackoverflow.com/questions/47425967/objectinputstream-constructor-hangs-program