File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Sockets and Internet Protocols and the fly likes question about socket encoding problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "question about socket encoding problem" Watch "question about socket encoding problem" New topic

question about socket encoding problem

zb cong
Ranch Hand

Joined: Jan 14, 2002
Posts: 416
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(
String inputLine = null;
while ((inputLine = in.readLine()) != null) {

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

Joined: Jul 03, 2001
Posts: 2120
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 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 ]

SCJP2. Please Indent your code using UBB Code
I agree. Here's the link:
subject: question about socket encoding problem
It's not a secret anymore!