在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。