伺服器到用戶端:
下面代碼是伺服器端把字元寫到Client端,經過gbEncoding()方法,所有的字元編碼成:\uXXXX.
代碼:
/**
* Write the String data
*
* @param out
* @param value
*/
public static void writeUnicode(final DataOutputStream out, final String value)
throws ActionException {
try {
final String unicode = StringFormatter.gbEncoding( value );
final byte[] data = unicode.getBytes();
final int dataLength = data.length;
System.out.println( "Data Length is: " + dataLength );
System.out.println( "Data is: " + value );
out.writeInt( dataLength );
out.write( data, 0, dataLength );
} catch (IOException e) {
throw new ActionException( IMDefaultAction.class.getName(), e.getMessage() );
}
}
以下代碼是gbEncoding()方法,把雙位元組字元轉換成\uXXXX,ASIIC碼在前面補00。
代碼:
/**
* This method will encode the String to unicode.
*
* @param gbString
* @return
*/
public static String gbEncoding( final String gbString ) {
char[] utfBytes = gbString.toCharArray();
String unicodeBytes = "";
for( int byteIndex = 0; byteIndex < utfBytes.length; byteIndex ++ ) {
String hexB = Integer.toHexString( utfBytes[ byteIndex ] );
if( hexB.length() <= 2 ) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "u" + hexB;
}
System.out.println( "unicodeBytes is: " + unicodeBytes );
return unicodeBytes;
}
在用戶端收到伺服器的資料,先將其一個一個字元解碼。雙位元組顯示正常。
代碼:
**
* This method will decode the String to a recognized String
* in ui.
* @param dataStr
* @return
*/
private StringBuffer decodeUnicode( final String dataStr ) {
int start = 0;
int end = 0;
final StringBuffer buffer = new StringBuffer();
while( start > -1 ) {
end = dataStr.indexOf( "u", start + 2 );
String charStr = "";
if( end == -1 ) {
charStr = dataStr.substring( start + 2, dataStr.length() );
} else {
charStr = dataStr.substring( start + 2, end);
}
char letter = (char) Integer.parseInt( charStr, 16 ); // 16進位parse整形字串。
buffer.append( new Character( letter ).toString() );
start = end;
}
return buffer;
}