3

I'm trying to program a chatting program. I ask you guys for help since I have little problem. when I try to send a CString formatted strings, it only receives first letter of the string. I'm using CAsyncSocket for sockets. I tried it with char* format string, it worked. Can you guys tell me what is wrong?

My code is like below:

worked.

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

not worked.

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

I've also tried:

CString a = _T("helloworld!");
char* buf = new char[a.GetLength()];
buf = (LPSTR)(LPCTSTR)a;
m_ClientSocket.Send(buf,a.GetLength()];
Andrew Komiagin
  • 6,446
  • 1
  • 13
  • 23
백경훈
  • 101
  • 4

1 Answers1

1

Here is the proper UNICODE-compliant way of doing it:

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());
Andrew Komiagin
  • 6,446
  • 1
  • 13
  • 23
  • Error: no suitable user-defined conversion from ATL::CW2A to CStringA exists my environment is visual studio 2015. – 백경훈 Oct 31 '15 at 09:49
  • Did you copy and paste the code snippet I've provided or did you modify it? Are you using Unicode Character Set in your project settings? The code compiles and works just fine in VS 2015. – Andrew Komiagin Oct 31 '15 at 10:00
  • 1
    First line should be `CStringW sMessage = L"Hello World";`. The calls to `GetBuffer`/`ReleaseBuffer` on *sMessageA* are not required, since you don't need **write** access. Casting to `BYTE*` (instead of `const BYTE*`) is the core of the issue. – IInspectable Oct 31 '15 at 12:21
  • Good catch. I've updated the code snippet to address your suggestions. – Andrew Komiagin Oct 31 '15 at 12:31