C++ Winsock unicode problem
I have just converted a program that uses winsock to unicode, and im running into a problem.
Here's my code, well part of it
TCHAR http_request[MAX_REQUEST_LEN];
TCHAR data[65536];
int nDataLen = 0;
/* Create http_request */
send(mySocket, (char*)http_request, lstrlen(http_request), 0)
nDataLen = recv(mySocket, (char*)data, 65536, 0);
I'm pretty sure casting data
to a char*
is causing the problem, thought i'm not completely sure.
There's no sendW or recvW so i'm wondering how i'm supposed to do this.
EDIT:
It's not crashing anymore thanks to Grim.
But now I've another problem, i've got this code but its returning ERROR_INVALID_PARAMETER
TCHAR http_request[MAX_REQUEST_LEN];
char ansi_data[65536];
TCHAR data[65536];
int nDataLen = 0;
/* Create http_request */
send(mySocket, (char*)http_request, lstrlen(http_request) * sizeof(TCHAR), 0);
n开发者_如何学运维DataLen = recv(mySocket, ansi_data, 65536, 0);
// Convert ansi_data to data, this is what causes the error
if (MultiByteToWideChar(CP_ACP, 0, ansi_data, nDataLen, data, 65536) == 0)
ErrorExit(GetLastError());
The main problem is that you are mixing up different concepts.
To get the correct program you have to know what you are doing instead of mechanically replace "char" with "TCHAR" in your entire code.
Your internal string representation and the data you are sending over the network is totally different things.
How you represent text data internally is your choice (whether it is ANSI or UNICODE16 or UTF-8 or whatever) and any choice is OK when you implement it consistently.
But the data you are sending over the network is totally different thing - its format is defined by the protocol you are using. Of course recv
function does not convert between character codings - it just sends data buffer over the network (as TCP connection data stream if you are using TCP socket). If you are sending HTTP request (as your variable name implies) then you have to use char
s (not TCHAR
s) because HTTP protocol uses ANSI characters.
You are probably having a problem with your send statement. send() expects the 3rd parameter to be size in bytes, you are giving it characters. While this works fine for ANSI strings (sizeof(char) == 1) it won't work correctly for UNICODE.
sizeof(wchar_t) == 2
The correct code should look like this:
send(mySocket, (char*)http_request, lstrlen(http_request)*sizeof(http_request[0]), 0);
You can't interchange char and TCHAR types, that would cause a problem. You either need to declare data as an array of char, or change recv to use TCHAR.
精彩评论