共计 1344 个字符,预计需要花费 4 分钟才能阅读完成。
在 Java 中解决 Socket 中文乱码问题可以使用以下方法:
- 使用 InputStreamReader 和 OutputStreamWriter 来处理字符流,可以指定字符编码方式。在发送和接收数据时,可以使用指定的字符编码方式进行解码和编码。
Socket socket = new Socket("localhost", 8080);
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(" 你好 ");
outputStreamWriter.flush();
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
char[] buffer = new char[1024];
int length = inputStreamReader.read(buffer);
System.out.println(new String(buffer, 0, length));
- 在发送和接收数据时,使用 getBytes() 方法和指定的字符编码方式进行编码和解码。
Socket socket = new Socket("localhost", 8080);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(" 你好 ".getBytes("UTF-8"));
outputStream.flush();
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int length = inputStream.read(buffer);
System.out.println(new String(buffer, 0, length, "UTF-8"));
- 在服务器端设置字符编码方式。
ServerSocket serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
char[] buffer = new char[1024];
int length = inputStreamReader.read(buffer);
System.out.println(new String(buffer, 0, length));
注意:在上述代码中,要确保发送和接收数据的编码方式一致,常用的编码方式有 UTF- 8 和 GBK。
丸趣 TV 网 – 提供最优质的资源集合!
正文完
发表至: Java
2023-12-13