在Java中解決Socket中文亂碼問題可以使用以下方法:
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));
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。