[英]java socket writeUTF() and readUTF()
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, the writer/reader stream do the things automatically for you. 我一直在阅读一些Java套接字代码片段,并且说明了在套接字通信中,为了按顺序发送消息,您不必手动分离它们,编写器/阅读器流会自动为您做事。 Here is an example:
这是一个例子:
writer.java
writeUTF("Hello");
writeUTF("World");
reader.java
String a=readUTF(); // a=Hello
String a=readUTF(); // b=World
I've tried this code snippet and it works fine. 我已经尝试过这段代码片段并且工作正常。 However, I'm wondering whether this kind of coding style is supposed to be working fine.
但是,我想知道这种编码风格是否应该正常工作。 Is there any potential risks of using the socket stream in sequence without explicitly seperating each segment?
是否存在按顺序使用套接字流而不明确分隔每个分段的潜在风险?
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. writeUTF()
和readUTF()
写入字符串的长度(以字节为单位,编码为UTF-8时),后跟数据,并使用修改后的UTF-8编码。 So there are some potential problems: 所以有一些潜在的问题:
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. 根据文档,
readUTF
和writeUTF
方法使用UTF8的修改版本,该版本还添加了要在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
. 这应该意味着读取操作将等待,直到返回足够的字符,然后才返回字符串。这意味着如果您没有看到它们,它们实际上也是分段的,因为您只是使用
DataInputStream
和DataOutputStream
来装饰套接字的流。
In conclusion, yes, it should be quite safe, since the API itself will take care of separating the single messages. 总之,是的,它应该是非常安全的,因为API本身将负责分离单个消息。
java.net.Socket
works fine, the stream waits readUTF();
java.net.Socket
工作正常,流等待readUTF();
But when using mina's CumulativeProtocolDecoder
, it won't, throws java.io.EOFException
但是当使用mina的
CumulativeProtocolDecoder
,它不会抛出java.io.EOFException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.