在 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 時中文亂碼的問題。