问题
I have server
ServerSocket socketListener = new ServerSocket(Config.PORT);
...
client = socketListener.accept();
and client
sock = new Socket("127.0.0.1", Config.PORT);
I want to transfer between them some serialized data using ObjectInputStream and ObjectOutputStream. When I try to do
ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
Nothing happens neither on the server side nor client side. Everything falls on that line. Both the client and the server is trying to get the input stream from the socket, but it does not work nor the client nor the server. How do I solve this problem so that I can pass the serialized data between client and server?
回答1:
As the javadoc says:
Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.
So, since both the server and the client start by opening an InputStream, you implemented a deadlock: they both block until the other party has sent the stream header. If you start by opening an ObjectInputStream at client side, you must start by opening an ObjectOutputStream (and flushing immediately if necessary) at server-side (or vice-versa).
来源:https://stackoverflow.com/questions/21075453/objectinputstream-from-socket-getinputstream