日期:2014-05-20  浏览次数:20744 次

Socket中文乱码问题,求助
这个是从客户端向服务器断写数据
class Write2Server extends Thread{
OutputStream out;
public Write2Server(OutputStream out){
this.out=out;
}
@Override
public void run() {
while(true){
Scanner scanner=new Scanner(System.in);
String time=new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date(System.currentTimeMillis()));
try {
out.write(("client"+"\t"+time+"\n"+scanner.nextLine()).getBytes());
out.write('\n');
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

这个是服务器端的读取
class ReadFromClient extends Thread{
InputStream in;
public ReadFromClient(InputStream in){
this.in=in;
}
public void run() {
int b;
try{
while((b=in.read())!=-1){
System.out.write(b);
}
}catch(Exception e){

}
}
}
然后问题就是在客户端输入中文,在服务端就乱码了,小菜一个,望大度赐教
------解决方案--------------------
自己先顶,怎么没人嘞,
------解决方案--------------------
你先检查下2个.java文件的编码是否相同,再检查下服务端和客户端的系统编码是否相同
------解决方案--------------------
你这个肯定上乱码,发送端把字符都转换成字节了,接收端应该把字节再组装成字符,之后再输出。
楼主直接把字节一个一个输出,遇到汉字,就是乱码了。
------解决方案--------------------
引用:
你这个肯定上乱码,发送端把字符都转换成字节了,接收端应该把字节再组装成字符,之后再输出。
楼主直接把字节一个一个输出,遇到汉字,就是乱码了。
那应该怎么做呀,我按着书上说的
------解决方案--------------------
这样改下试试:
我没测试
class ReadFromClient extends Thread{
        InputStream in;
        public ReadFromClient(InputStream in){
            this.in=in;
        }
        public void run() {
            byte[] b1=new byte[32];//缓冲数组
    int b;
            try
    {
                while((b=in.read(b1))!=-1){
String s=new String(b1,"gbk");//组成字符串。
                    System.out.write(s);
                }
            }catch(Exception e){
                 
            }
        }
    }

------解决方案--------------------
引用:
这样改下试试:
我没测试
Java code?12345678910111213141516171819class ReadFromClient extends Thread{        InputStream in;        public ReadFromClient(InputStream in){            this.in=in;     ……