Last few chars in a string sent over socket sometimes missing in Java network program

后端 未结 3 633
野趣味
野趣味 2021-01-24 14:36

Right now, I\'m trying to write a GUI based Java tic-tac-toe game that functions over a network connection. It essentially works at this point, however I have an intermittent er

相关标签:
3条回答
  • 2021-01-24 15:15

    As it turns out, the ready() method guaruntees only that the next read WON'T block. Consequently, !ready() does not guaruntee that the next read WILL block. Just that it could.

    I believe that the problem here had to do with the TCP stack itself. Being stream-oriented, when bytes were written to the socket, TCP makes no guarantees as to the order or grouping of the bytes it sends. I suspect that the TCP stack was breaking up the sent string in a way that made sense to it, and that in the process, the ready() method must detect some sort of underlying break in the stream, and return false, in spite of the fact that more information is available.

    I refactored the code to add a newline character to every message send, then simply performed a readLine() instead. This allowed my network protocol to be dependent on the newline character as a message delimiter, rather than the ready() method. I'm happy to say this fixed the problem.

    Thanks for all your input!

    0 讨论(0)
  • 2021-01-24 15:35

    Try flushing the OutputStream on the sender side. The last bytes might remain in some intenal buffers.

    0 讨论(0)
  • 2021-01-24 15:41

    It is really important what types of streamed objects you use to operate with data. It seems to me that this troubleshooting is created by the fact that you use DataOutputStream for sending info, but something else for receiving. Try to send and receive info by DataOutputStream and DataInputStream respectively.

    Matter fact, if you send something by calling dataOut.writeBoolean(b) but trying to receive this thing by calling dataIn.readString(), you will eventually get nothing. DataInputStream and DataOutputStream are type-sensitive. Try to refactor your code keeping it in mind.

    Moreover, some input streams return on invocation of read() a single byte. Here you try to convert this one single byte into char, while in java char by default consists of two bytes.

           msgChar = (char)dataIn.read();
    

    Check whether it is a reason of data loss.

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