D
D
Daniel2018-10-17 21:03:10
C++ / C#
Daniel, 2018-10-17 21:03:10

Hangs on recv c++ winsock2?

In the loop, I read data into the buffer when all the data has already been received, that is, the penultimate call returned 1-10 bytes, it is called because reads_bytes>0 , and there is nothing to read there, and the program freezes, how to exit the loop?

while ((reads_bytes = c->recv(buf, len)) > 0) {
       std::cout.write(buf, reads_bytes);	
      // if (reads_bytes<len) break; // можно так но подозрительно
     }
/////////////////////////////////////////////////////////////////////////////////
int Socket::recv(char * buf, int  len)
{
  int read_bytes = ::recv(this->socket_id, buf, len, 0); // зависает после того как читать не чего, но она зупустилась уже
  if (read_bytes ==SOCKET_ERROR) {
    close();
    error("recv failed "+ WSAGetLastError());
  }
  if (read_bytes == 0) {
    close();
    return -1;
  }
  return read_bytes;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2018-10-17
@15432

Well, here are the various options:
1) set a timeout for receiving
2) rewrite to non-blocking sockets
3) do not accept anything extra (accept a header, see how much data is, receive data of exactly the right size)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question