This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question about socket encoding problem

 
zb cong
Ranch Hand
Posts: 416
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello
see my code bellow:

ServerSocket server = new ServerSocket(10001);
Socket socket = server.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}

as you can see,this is a socket server code snippet,it works well,but if the client send different encoding info from mine,such as "utf-8",the info can't be display correctly.
who can tell me how i can modify my code to recapsulate the input to my local encoding("GBK"),and make it is perfectly displyed?
thank you!
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you happen to know whether all your clients are going to use the same charset?
If so you could use at the reading edge something like:
new BufferedInputStream(new InputStreamReader(socket.getInputStream(), encoding));
Where encoding is a String representing the name or the alias of a java.nio.charset.Charset object. Look at the API for Charset.name() or Charset.aliases()
Still System.out.println(inputLine); is unlikely to work:
System.out is a PrintStream. This class uses the platform's default character encoding. If this is not the same as the one denoted by "encoding"
it will be useless.
Thus we could use someting like:
new PrintWriter(new OutputStreamWriter(System.out(), "encoding"));
Beautiful but wrong when writting to a DOS console. There are no guarantees that a DOS window supports such encoding. I think you will be safer by just adding inputLine to a JTextArea.
[ April 23, 2004: Message edited by: Jose Botella ]
[ April 23, 2004: Message edited by: Jose Botella ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic