user3366592
user3366592

Reputation: 449

c++ winsock - recv() returns incorrect and strange buffer

I am writing a simple game named "TicTacToe". I also wanted to create a network function using WinSock. While connection between two users goes without errors, I can't receive any correct data. After receiving it, the buffer is filled with a strange characters like "☺$0/A", etc., while it should receive "Hello!".

Here's my code:

const char buf[] = "Hello!";
char rbuf[16];
int bytes = 0;
memset(buf, 0, sizeof(buf));

// sending

send(sox, buf, sizeof(buf), 0);

// recv

bytes = recv(sox, rbuf, 16, 0)
rbuf[bytes] = '\0';
cout << rbuf << endl;

Upvotes: 0

Views: 1545

Answers (1)

user2527098
user2527098

Reputation:

Well, for one, you're not checking the return values of your send/recv calls, also you can't expect it to always receive 16 bytes. In order to ensure you get what you want to receive, you might have to call recv multiple times. Here's an example solution to that problem:

int FixedRecv(SOCKET sox, char* rbuf, int length)
{
    int ref, len = 0;
    do {
        ref = recv(sox, rbuf + len, length - len, 0);

        if(ref == 0) return 0;

        if(SOCKET_ERROR != ref)
            len += ref;
        else return SOCKET_ERROR;
    } while(len < length);

    return len;
}

Same will also apply to your calls to send but I just want you to get a general idea.


Hope that helps, uses a little bit of pointer arithmetic, but nothing
too extensive.

Also, if you're using nonblocking sockets, you will want to check for WSAEWOULDBLOCK with WSAGetLastError.

Upvotes: 1

Related Questions