简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM