【问题标题】:How to send CString through sockets?如何通过套接字发送 CString?
【发布时间】:2016-01-31 16:21:42
【问题描述】:

我正在尝试编写一个聊天程序。 由于我的问题不大,所以请大家帮忙。 当我尝试发送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()];

【问题讨论】:

    标签: sockets mfc c-strings


    【解决方案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());
    

    【讨论】:

    • 错误:不存在从 ATL::CW2A 到 CStringA 的合适的用户定义转换我的环境是 Visual Studio 2015。
    • 您是复制粘贴我提供的代码 sn-p 还是您修改了它?您是否在项目设置中使用 Unicode 字符集?该代码在 VS 2015 中编译并运行良好。
    • 第一行应该是CStringW sMessage = L"Hello World";。不需要在 sMessageA 上调用 GetBuffer/ReleaseBuffer,因为您不需要 write 访问权限。投射到BYTE*(而不是const BYTE*)是问题的核心。
    • 好收获。我已经更新了代码 sn-p 以解决您的建议。
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2021-09-15
    • 2018-01-22
    • 2014-04-29
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多