Winsock IRC client connects but does not send data
I开发者_如何学JAVA'm using the code posted on http://social.msdn.microsoft.com/Forums/en/vcgeneral/thread/126639f1-487d-4755-af1b-cfb8bb64bdf8 but it doesn't send data just like it says in the first post. How do I use WSAGetLastError() like it says in the solution to find out what's wrong?
I tried the following:
void IRC::SendBuf(char* sendbuf)
{
int senderror = send(m_socket, sendbuf, sizeof(sendbuf), MSG_OOB);
if(senderror == ERROR_SUCCESS) {
printf("Client: The test string sent: \"%s\"\n", sendbuf);
}
else {
cout << "error is: " << senderror << ", WSAGetLastError: " << WSAGetLastError() << endl;
printf("Client: The test string sent: \"%s\"\n", sendbuf);
}
}
And the output is: error is: 4, WSAGetLastError: 0
You're evaluating the address of WSAGetLastError instead of calling it. You need to add parenthesis in order to actually call that function:
void IRC::SendBuf(char* sendbuf)
{
int senderror = send(m_socket, sendbuf, strlen(sendbuf), 0);
if (senderror != SOCKET_ERROR) {
printf("Client: The test string sent: \"%s\"\n", sendbuf);
} else {
cout << "Error is: " << WSAGetLastError() << endl;
}
}
EDIT: The send() function returns the number of bytes written, not an error code. You need to test the return value against SOCKET_ERROR
, as in the updated code above. In your case, send()
tells that it successfully sent 4 bytes.
As you noted below, it only sends 4 bytes because that's the size of the sendbuf
variable (it's a pointer, not a buffer). If the string in sendbuf
is null-terminated, you can use strlen()
instead. If it isn't, you probably should add a string length parameter to IRC::SendBuf()
itself.
精彩评论