如何通过套接字发送CString?

时间:2015-10-31 08:27:31

标签: sockets mfc c-strings

我正在尝试编写聊天程序。 我问你们帮忙,因为我没有什么问题。 当我尝试发送CString格式化的字符串时,它只接收字符串的第一个字母。 我使用CAsyncSocket作为套接字。 我用char*格式字符串尝试了它,它起作用了。 你们能告诉我出了什么问题吗?

我的代码如下:

的工作。

char* buf = new char[m_strMsg.GetLength()];
buf = "helloworld!";
m_ClientSocket.Send("sended", m_strMsg.GetLength());
m_ClientSocket.Send(buf, 10);

没有工作。

CString a = _T("helloworld!");
m_ClientSocket.Send(a,10);

我也尝试过:

CString a = _T("helloworld!");
char* buf = new char[a.GetLength()];
buf = (LPSTR)(LPCTSTR)a;
m_ClientSocket.Send(buf,a.GetLength()];

1 个答案:

答案 0 :(得分:1)

符合UNICODE标准的方法如下:

CStringW sMessage = L"Hello World";
// convert from UTF-16 (UCS-2) to UTF-8
CStringA sMessageA = CW2A(sMessage, CP_UTF8);
const size_t nBytes = sizeof(CStringA::XCHAR) * sMessageA.GetLength();
CByteArray Message; 
Message.SetSize( nBytes );
std::memcpy( Message.GetData(), (const BYTE*)(LPCSTR)sMessageA, nBytes );
m_ClientSocket.Send(Message.GetData(), Message.GetSize());