Search code examples
c++unicodemfcclient-serverasyncsocket

CSocket Client-Server String recieved is chinese looking characters


Simple CAsyncSocket Server and client program. Right now I'm testing locally using tera term vt. So I type a word in TT and it gets sent to my program but the string I receive is just a bunch of Chinese characters. I'm using MFC and compiling in Unicode. Now the funny thing is when I comply with multibyte character set the string is received just fine so I'm not sure what that means or what I can change to get that result.

Code where the receiving happens

void CClientSock::OnReceive(int nErrorCode)
{
TCHAR buf[1000];
memset(buf,'\0',1000);
CString recStr;
int bytesRead;
bytesRead = Receive(buf,1000);

switch(bytesRead)
{
case 0:
    Close();
    break;
case SOCKET_ERROR:
    if(GetLastError() != WSAEWOULDBLOCK)
    {
        AfxMessageBox(L"Error occured");
        Close();
    }
    break;
default:
    buf[bytesRead] = '\0';
    CString temp(buf);
    recStr = temp;

    CT2A Astring(recStr);
    CString nString(Astring);
    AfxMessageBox(nString);

}
        CAsyncSocket::OnReceive(nErrorCode);
}

Solution

  • The data that you received from CAsyncSocket::Receive is probably multi-byte character, so just replace the TCHAR buf[1000]; with char buf[1000];

    You also have created too many redundant CStrings for text conversion. It can be simplied to:

    default:
        buf[bytesRead] = '\0';
        recStr = buf;
        AfxMessageBox(recStr);