[分享]解决C++ client socket send to Workerman 中文乱码问题

egirlasm

在windows上 用正常的socket
[code]send(s,"你好世界",4,0);[/code]
这样workerman服务器收到的始终是乱码.这是因为workerman里使用的都是 utf-8

因此发送之前,一定要。[code]string UnicodeToUTF8(const wstring& str)
{
char* pElementText;
int iTextLen;
// wide char to multi char
iTextLen = WideCharToMultiByte(936,
0,
str.c_str(),
-1,
NULL,
0,
NULL,
NULL);
pElementText = new char[iTextLen + 1];
memset((void[i])pElementText, 0, sizeof(char) [/i] (iTextLen + 1));
::WideCharToMultiByte(CP_UTF8,
0,
str.c_str(),
-1,
pElementText,
iTextLen,
NULL,
NULL);
string strText;
strText = pElementText;
delete pElementText;
return strText;
}

wstring str = L"你好世界";
string utf8str = UnicodeToUTF8(str);
send(s,utf8str.cstr(),utf8str.length(),0);
[/code]上面的会被截断一部分文字,故把字节buffer弄大了一点,就没问题了。
修正如下,[code]string UnicodeToUTF8(const wstring& str)
{
char pElementText;
int iTextLen;
// wide char to multi char
iTextLen = WideCharToMultiByte(936,
0,
str.c_str(),
-1,
NULL,
0,
NULL,
NULL);
pElementText = new char[iTextLen
2 + 1];
memset((void[i])pElementText, 0, sizeof(char) [/i] (iTextLen2 + 1));
::WideCharToMultiByte(CP_UTF8,
0,
str.c_str(),
-1,
pElementText,
iTextLen
2,
NULL,
NULL);
string strText;
strText = pElementText;
delete pElementText;
return strText;
}[/code]

4041 1 0
1个评论

walkor

感谢@egirlasm的分享

  • 暂无评论
年代过于久远,无法发表评论

egirlasm

2030
积分
0
获赞数
0
粉丝数
2016-11-17 加入
🔝