在 MFC 中使用 Java 的 Socket 进行通信时,中文乱码问题可能出现在两个方面:发送端和接收端。下面给出解决方法:
发送端:
CString str = _T("中文字符");
std::string utf8Str = CW2A(str.GetString(), CP_UTF8);
jbyteArray byteArray = env->NewByteArray(utf8Str.length());
env->SetByteArrayRegion(byteArray, 0, utf8Str.length(), reinterpret_cast<jbyte*>(const_cast<char*>(utf8Str.c_str())));
env->CallVoidMethod(javaSocket, sendMethod, byteArray);
接收端:
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
String receivedData = new String(buffer, 0, len, "UTF-8");
System.out.println("Received data: " + receivedData);
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
String receivedData = new String(buffer, 0, len, "GBK");
System.out.println("Received data: " + receivedData);
通过上述方法,可以解决 MFC Java 使用 Socket 时中文乱码的问题。