PROBLEM SENDING UTF - 8 STRING ACROSS SOCKETS
I have been having a problem with sending a string over a socket
auth_send="$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |$Direction Upload 16836|$Key ?#9572;└◄░?#9658;►A ╤▒▒└└0╨0► 0► 0► 0► 0► 0►|";
as it can be seen the string has both encoded chars as well as default chars.
Question :
How do I send this over a socket so that it doesnt get altered?
I used :
OutputStream reply;
reply=dwnld_send.getOutputStream();//dwnld_send is a socket already defined
byte[] buffer1=new byte[500];
int j=0;
while(auth_send.charAt(j)!='?')
{
buffer[j]=(byte)(auth_send.charAt(j));
j++;
}
reply.write(buffer, 0,j);
System.out.println("");
System.out.write(buffer, 0,j);
System.out.println("");
/*
System.out.write(buffer, 0,j); GENERATED AN ALTERED STRING IN WHICH THE ENCODED PART OF STRING GOT CHANGED*/
please help
> auth_send="$Supports MiniSlots XmlBZList ADCGet TTHL
> TTHF GetZBlock ZLIG |$Direction Upload 16836|$Key
> ?#9572;└◄░?#9658;►A
> ╤▒▒└└0╨0►
> 0► 0► 0► 0► 0►|";
>
It's not safe to use non-ASCII characters in source code. The compiler always assumes that the file is in the platform default encoding, which naturally varies from platform to platform. Unicode characters can always be encoded in ASCII using \uXXXX-ecape secuences, for example ► is \u25ba. You can use the native2ascii tool to translate files to this format.
> OutputStream reply;
> reply=dwnld_send.getOutputStream();//dwnld_send is a
> socket already defined
>
To send and receiver characters/text you should use the writer and reader classes; plain streams are for passing any binary data. See
http://java.sun.com/docs/books/tutorial/essential/io/charstreams.html
http://java.sun.com/docs/books/tutorial/networking/sockets/readingWriting.html
In order to use UTF-8 you need to pass the string "UTF-8" as the second parameter to the constructors of InputStreamReader and OutputStreamWriter. Code examples:
http://www.exampledepot.com/egs/java.io/WriteToUTF8.html
http://www.exampledepot.com/egs/java.io/ReadFromUTF8.html?l=rel
For some reason you are converting chars to bytes using the castbuffer[j]=(byte)(auth_send.charAt(j));
which will convert any chars outside of the range 0x00 to 0xff to bytes in this range.
You can wrap your stream in a Writer and write the string directly
Writer writer = new OutputStreamWriter(reply, "utf-8"));
writer.write(auth_send);