user1157885
user1157885

Reputation: 2069

Socket RECV stuck in loop

I have the following code:

while (true)
{
    recv(server, buffer, BUFFER_LENGTH, 0);
    cout << buffer;
}

What I expect to happen is when my client sends data to the server for it to receive the data, output it and then go back to trying to receive more data but it never actually reaches the cout line. If I remove the loop it works fine, why is the while loop making RECV never end..?

Send code:

while (true)
{
    cin >> buffer;
    send(client, buffer, BUFFER_LENGTH, 0);
}

Thanks

Upvotes: 1

Views: 2281

Answers (2)

Danny_ds
Danny_ds

Reputation: 11406

First, you always have to check the return value of recv().

Then, if you're using std::cout you have to make sure your buffer is null-terminated.

recv() will block as long as there is no data, or an error (or connection closed, timeout, etc) occurs.

Update (Send code added)

cin >> buffer;

-> your buffer could overflow here..

send(client, buffer, BUFFER_LENGTH, 0);

-> here also: always check the return code.

Upvotes: 1

cadaniluk
cadaniluk

Reputation: 15229

std::cout is buffered, so the output is not directly visible.
Try

std::cout << buffer << std::flush;

instead.

As to why the loop never ends: by default, sockets are in blocking mode, so the recv will wait as long as there is some data available and only return then.
You have to move your server socket into non-blocking mode or just read once.

Upvotes: 1

Related Questions