将我的服务器响应char数组转换为wchar_t数组是处理客户端收到的服务器消息的正确方法吗?

Is converting my server response char array to a wchar_t array the correct way to handle the server message my client receives?

本文关键字:服务器 数组 消息 方法 客户端 转换 char 响应 我的 wchar 处理      更新时间:2023-10-16

我是c++、windows编程和这些论坛的新手(很抱歉违反了程序),过了一段时间我还没能找到这个问题的答案,所以这里开始了…

我正在写一个小聊天程序,它目前包括一个服务器,等待客户端连接,当客户端连接时,它发送消息"你已经连接!"。客户端是一个Win32应用程序,它自动连接到服务器,接收连接消息,并将其装入多行文本框中。

我有它的工作,但我不得不使用一些代码将服务器响应转换为wchar_t,我这样做的方式对我来说感觉不对。是否有更好的方法来设置客户端或服务器,或者我这样做是正确的?

这是相关的服务器代码…

    ...
    //JMP_:sListen and sConnect are both = socket(AF_INET, SOCK_STREAM,NULL);
    if(sConnect = accept(sListen, (SOCKADDR*)&addr, &addrlen)){
        cout << "A connection was found" << endl;
        send(sConnect,"You have connected!", 20, NULL);
    }
    ...

这里是我为服务器响应声明char数组的代码位…

    ...
    // includes up here
    char serverresponse[255];
    // WinMain down here
    ...

和从服务器接收消息的代码位…

    ...
    //JMP_: this is in the WinMain function.
    connect(sConnect, (SOCKADDR*)&addr, sizeof(addr));
recv(sConnect, serverresponse, sizeof(serverresponse), NULL);
getchar();
    ...

最后一段代码是我将服务器响应放入文本框的地方…

    ...
    // JMP_: this is in WndProc
    case WM_CREATE:
        {
         // Create an edit box
        hwndEdit = CreateWindowEx(0, _T("EDIT"),
            NULL,
            WS_CHILD|WS_VISIBLE|WS_VSCROLL |
            ES_LEFT | ES_MULTILINE|ES_AUTOVSCROLL,
            50, 100, 200, 100,
            hWnd,
            (HMENU) ID_EDITCHILD,
            (HINSTANCE) GetWindowLong(hWnd, GWL_HINSTANCE),NULL);
        //JMP_: I just pulled this indented bit from MSDN
            // Convert to a wchar_t*  
            size_t origsize = strlen(serverresponse) + 1;
            const size_t newsize = 100;
            size_t convertedChars = 0;
            wchar_t wcstring[newsize];
            mbstowcs_s(&convertedChars, wcstring, origsize, serverresponse, _TRUNCATE);
        //
        // Add text to the window. 
        SendMessage(hwndEdit, WM_SETTEXT, 0,  (LPARAM) wcstring);
        return 0;
        }

您必须将服务器响应转换为wchar_t的原因是因为您将客户端代码构建为Unicode构建,随后所有对期望任何来自car*或wchar*的窗口的api调用都是Unicode上的#ifdef,常规名称被预处理器取代,其名称以W (Unicode)或a(非Unicode)结尾。正如马茨·彼得森指出的那样。因此,当您从调用recv将数据塞入char*数组时,您将不得不将其转换为wchar_t以显示在文本框或任何其他windows UI控件中。在unicode项目中使用窄字符api是'ok'的(因为windows会在幕后为您将其转换为unicode),但如果快速连续完成,可能会导致一些潜在的性能问题。