I am reading a java program, when it sending messages through socket, it awa开发者_如何学Cys convert String to byte array before sending out:
public static void write(String msg, OutputStream out) {
out.write (msg.getBytes("ASCII"));
}
Since I am a C++ programmer, I don't know what is the advantage to do so in java. Could anyone tell me?
Java's string type is Unicode: a string is a sequence of characters (actually, "code points") rather than of bytes. In order to send that correctly over the network, you need to have some convention for how those code points (of which there are about a million) are to be represented as bytes. But if you happen to know that your string is entirely ASCII you can take the simple way out, as seen in the code you posted, of assuming that all code points fit within a single byte.
Because Socket was designed to write bytes in it using OutputStream
. The JavaDoc for OutputStream states:
An output stream accepts output bytes and sends them to some sink.
Unlike C++, String are represented in UTF-16 format and is a sequence of Characters java.lang.CharSequence
and not just an array of ASCII characters (like C++). It's henceforth, why it's necessary to encode the String to your desirable encoding (in your instance, ASCII).
In Java, strings are always internally Unicode. Therefore, you can't directly write a string to a binary stream without encoding it (at least in theory) since there is no "native" representation like the 8bit ascii-and-whatever "chars" in other languages.
Because sockets (at the system level) deal in bytes. This is the same in C or C++ or anything else using the system socket libraries.
In Java, however, you can abstract that away, for example:
BufferedWriter out =
new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedWriter includes a write(String s, int off, int len)
method.
You can directly write strings to a Stream, but you have to use a special type of 'filtering' stream called an ObjectOutputStream.
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
oos.writeObject("Foo");
Of course, using this, the string is not formatted just like an array of bytes, but uses a proprietary format that only ObjectInputStream should know. This Stream type can be used to write any arbitrary Serializable object, not just Strings.
精彩评论