ObjectInputStream from socket.getInputStream()

二次信任 提交于 2020-01-21 10:15:05

问题


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

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