java socket writeUTF() and readUTF()

后端 未结 3 1537
北恋
北恋 2020-12-14 23:06

I\'ve been reading some Java socket code snippet and fonund out a fact that in socket communication, to send messages in sequence, you don\'t have to seperate them by hand,

相关标签:
3条回答
  • 2020-12-14 23:32

    java.net.Socket works fine, the stream waits readUTF();

    But when using mina's CumulativeProtocolDecoder, it won't, throws java.io.EOFException

    0 讨论(0)
  • 2020-12-14 23:37

    According to the documentation the readUTF and writeUTF methods work with a modified version of UTF8 that also adds the length of the character to be read in the beginnig.

    This should mean that the read operation will wait until enough characters had been fetched before returning the string.. this means they are actually segmented also if you don't see it since you merely decorate the streams of the socket with the DataInputStream and DataOutputStream.

    In conclusion, yes, it should be quite safe, since the API itself will take care of separating the single messages.

    0 讨论(0)
  • 2020-12-14 23:39

    The writeUTF() and readUTF() write the length of the String (in bytes, when encoded as UTF-8) followed by the data, and use a modified UTF-8 encoding. So there are some potential problems:

    • The maximum length of Strings that can be handled this way is 65535 for pure ASCII, less if you use non-ASCII characters - and you cannot easily predict the limit in that case, other than conservatively assuming 3 bytes per character. So if you're sure you'll never send Strings longer than about 20k, you'll be fine.
    • If the app ever needs to communicate with something else (that's not written in Java), the other side may have a hard time handling the modified UTF-8. For application-internal communication, you don't have to worry though.
    0 讨论(0)
提交回复
热议问题