MFC `CAsyncSocket::ReceiveFrom` 接收 UDP 數據,預期接收字符串,實際僅收到**第一個字節**(如發送 "Hello",僅收到 'H')。
項目屬性 **Character Set = Unicode** (默認),導致:
void CChatDlg::OnBnClickedSendButton() {
CString str;
GetDlgItemText(IDC_SEND_EDIT, str);
// Unicode (wchar_t) → UTF-8 (char*)
int len = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
char* utf8 = new char[len];
WideCharToMultiByte(CP_UTF8, 0, str, -1, utf8, len, NULL, NULL);
m_sock.SendTo(utf8, len - 1, PORT, sIP); // 發送實際字節數,不含結束符
delete[] utf8;
}
void CChatDlg::OnReceive(int nErrorCode) {
char s[1024];
CString sIP; UINT nPort;
int nRecv = m_sock.ReceiveFrom(s, sizeof(s) - 1, sIP, nPort);
if (nRecv > 0) {
s[nRecv] = '\0';
// UTF-8 → Unicode 顯示
int len = MultiByteToWideChar(CP_UTF8, 0, s, nRecv, NULL, 0);
wchar_t* wbuf = new wchar_t[len + 1];
MultiByteToWideChar(CP_UTF8, 0, s, nRecv, wbuf, len);
wbuf[len] = L'\0';
CString str(wbuf);
delete[] wbuf;
// 顯示到編輯框...
}
}
項目屬性 → General → Character Set → **Use Multi-Byte Character Set**。但不推薦,現代 Windows 開發應統一 Unicode 內部,邊界處理編碼轉換。
| 函數 | 用途 | 關鍵參數 |
|---|---|---|
| WideCharToMultiByte | Unicode → ANSI/UTF-8 | CP_UTF8 / CP_ACP |
| MultiByteToWideChar | ANSI/UTF-8 → Unicode | CP_UTF8 / CP_ACP |
| CString::GetLength | 返回字符數(非字節數) | Unicode下每字符2字節 |
| sizeof(buffer) | 返回字節數 | char[256] → 256 |