将我的服务器响应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?
我是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),但如果快速连续完成,可能会导致一些潜在的性能问题。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- 使用 ESP8266/8285 将字符串从 Web 服务器转换为字节数组
- TCP C++客户端从C#服务器接收字节数组
- 如何使用 WIN RPC 发送终止的字符数组(用于将图像从客户端上传到服务器)
- 使用套接字从 Python(客户端)发送到 C++(服务器)数组的数据
- 将 cv::Mat 存储在字节数组中,以便将数据传输到服务器
- C++ 将请求发送到 Web 服务器上的 API,然后接收 JSON 数组响应
- 将char数组从c++(客户端)传递到python(服务器)winsock
- c++在服务器和客户端程序中使用字符数组
- COM服务器作为windows服务,不能将数组作为函数参数传递
- C++ wxsocket TCP 服务器发送无符号字符数组,但 python 客户端再获得 4 个字节
- 将我的服务器响应char数组转换为wchar_t数组是处理客户端收到的服务器消息的正确方法吗?