溫馨提示×

java中socket中文亂碼怎么解決

小億
190
2023-11-10 09:38:52
欄目: 編程語言

在Java中解決Socket中文亂碼問題可以使用以下方法:

  1. 使用InputStreamReader和OutputStreamWriter來處理字符流,可以指定字符編碼方式。在發(fā)送和接收數(shù)據(jù)時(shí),可以使用指定的字符編碼方式進(jìn)行解碼和編碼。
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));
  1. 在發(fā)送和接收數(shù)據(jù)時(shí),使用getBytes()方法和指定的字符編碼方式進(jìn)行編碼和解碼。
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"));
  1. 在服務(wù)器端設(shè)置字符編碼方式。
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));

注意:在上述代碼中,要確保發(fā)送和接收數(shù)據(jù)的編碼方式一致,常用的編碼方式有UTF-8和GBK。

0