ObjectInputStream/ObjectOutputStream work not right

后端 未结 3 2063
轻奢々
轻奢々 2020-12-12 04:44

I have classes: Client, Server and Background is working with Player class. I really don\'t understand why my Client class with ObjectInputStream/ObjectOu

相关标签:
3条回答
  • 2020-12-12 04:55

    You need to construct the ObjectOutputStream before the ObjectInputStream, at both ends. At present you have a deadlock.

    You also need to move the closes outside the loops.

    0 讨论(0)
  • 2020-12-12 05:03

    You are closing the stream in a loop. You can't use a stream or any resource after it has been closed.

    0 讨论(0)
  • 2020-12-12 05:09

    Ok, this is how object streams work and the solution that works everywhere.

    Object stream data is preceded by a 4 byte 'magical' sequence AC ED 00 05. An ObjectInputStream will peek for this data at construction time rather than before the first read. And that's logical: one wants to be sure it is a proper stream before being too far in an application. The sequence is buffered by the ObjectOutputStream at construction time so that it is pushed on the stream at the first write. This method often leads to complexities in buffered situations or transferring via pipes or sockets. Fortunately there is a just as simple as effective solution to all these problems:

    Flush the ObjectOutputStream immediately after construction!

    ObjectOutputStream myStream = new ObjectOutputStream ( anotherStream );
    myStream.flush();
    

    In your case in both client and server apps.

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