Thread hangs when creating ObjectInputStream

后端 未结 1 1975
感动是毒
感动是毒 2021-01-19 02:43

I\'ve got the following code on my server end:

public class ClientThread extends Thread
{
Socket clientSocket;

DataInputStream dis;
ObjectI         


        
相关标签:
1条回答
  • 2021-01-19 03:25

    Just calling getInputStream() isn't 'reading', and it doesn't cause this problem. You can prove that by calling it ten times, or constructing ten DataInputStreams round it. It is the construction of the ObjectInputStream that is causing the problem, and you can prove that by removing the DataInputStream altogether, which you should do anyway: see below.

    You're creating an ObjectInputStream. The constructor of ObjectInputStream reads a stream header that is written by the constructor of ObjectOutputStream. As that isn't happening in this code, and presumably not at the peer either, it blocks forever.

    For the same reason, you must create the ObjectOutputStream first, before the ObjectInputStream, otherwise again you will have a deadlock.

    There seems to be some plan here to use two kinds of stream on the same socket. Don't do that. It won't work, and it isn't necessary, as the object streams have all the same methods as the data streams, in addition to the object reading and writing methods.

    EDIT Now that you've posted your client code, what is happening is that the client is deferring creation of the ObjectOutputStream until call() is called. It should be created in the constructor of that class. Otherwise your server side constructor blocks until call() is called at the client. And you still need to get rid of the redundant streams.

    0 讨论(0)
提交回复
热议问题