关于TCP的字节流转字符流

TCP客服端的接收中:

 1     public static void main(String[] args) throws IOException {
 2         ServerSocket ss = new ServerSocket(10000);
 3         Socket accept = ss.accept();
 4         InputStream inputStream = accept.getInputStream();
 5         int len;
 6 //        byte[]bytes=new byte[1024];
 7         while ((len = inputStream.read(/*bytes*/)) != -1) {//一个字节一个字节的读
 8 //            System.out.println(new String(bytes,0,len));
 9             System.out.println((char)len);//一个字节一个字节的打印,如果是英文字母则不会出现乱码的问题,但是如果是中文则会出现乱码的问题
10         }
11         inputStream.close();
12         accept.close();
13         ss.close();
14 
15 
16     }

 中文乱码:

如果客服端是英文的话:

 1     public static void main(String[] args) throws IOException {
 2         Socket socket = new Socket("127.0.0.1", 10000);
 3         String s = "Coder0927";
 4         OutputStream outputStream = socket.getOutputStream();
 5         outputStream.write(s.getBytes());
 6         outputStream.close();
 7         socket.close();
 8 
 9 
10     }

则服务器的运行结果是:

并不会出现乱码,但是如果客户端发送的是中文时:

 1     public static void main(String[] args) throws IOException {
 2         Socket socket = new Socket("127.0.0.1", 10000);
 3         String s = "迎风少年";
 4         OutputStream outputStream = socket.getOutputStream();
 5         outputStream.write(s.getBytes());
 6         outputStream.close();
 7         socket.close();
 8 
 9 
10     }

 运行结果就会出现乱码:

 解决办法一:

如果服务器不是一个字节一个字节的读取就不会出现乱码的问题(先用一个byte[]数组装字节)

代码如下:

 1     public static void main(String[] args) throws IOException {
 2         ServerSocket ss = new ServerSocket(10000);
 3         Socket accept = ss.accept();
 4         InputStream inputStream = accept.getInputStream();
 5         int len;
 6         byte[]bytes=new byte[1024];
 7         while ((len = inputStream.read(bytes)) != -1) {
 8             System.out.println(new String(bytes,0,len));
 9 
10         }
11         inputStream.close();
12         accept.close();
13         ss.close();
14 
15 
16     }

运行结果:

解决方法二:

将得到的字节流转换为字符流:

代码如下:

 1     public static void main(String[] args) throws IOException {
 2         ServerSocket ss = new ServerSocket(10000);
 3         Socket accept = ss.accept();
 4 
 5        /* int len;
 6         byte[]bytes=new byte[1024];
 7         while ((len = inputStream.read(bytes)) != -1) {
 8             System.out.println(new String(bytes,0,len));
 9 
10         }*/
11         BufferedReader br = new BufferedReader(new InputStreamReader(accept.getInputStream()));//转换流
12         String line;
13         while ((line = br.readLine()) != null) {
14             System.out.println(line);
15 
16 
17         }
18 
19 
20         br.close();
21         accept.close();
22         ss.close();
23 
24 
25     }

运行结果:

迎风少年
原文地址:https://www.cnblogs.com/ZYH-coder0927/p/13523019.html