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

后端 未结 3 634
野趣味
野趣味 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题