Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

c++ - Winsock recv() does not block

I have just compiled this code: http://www.win32developer.com/tutorial/winsock/winsock_tutorial_2.shtm

I have added some codes so it does recv(), in an infinite loop. My problem, if there is no data to read, it still does not block.

Am I totally mistaken if I think recv should block in my case?

The code I have added is:

for(;;)
{
  char buffer[1000];
  memset(buffer,0,999);
  int inDataLength = recv(Socket,buffer,1000,0);

  int nError=WSAGetLastError();
  if(nError!=WSAEWOULDBLOCK&&nError!=0)
  {
    std::cout<<"Winsock error code: "<<nError<<"
";
    std::cout<<"Client disconnected!
";

    // Shutdown our socket
    shutdown(Socket,SD_SEND);

    // Close our socket entirely
    closesocket(Socket);

    break;
  }
}

It is at the end, after the std::cout<<"Client connected! "; line. I know I copied this from a "non blocking" example, but I dont think this code should do anything nonblocking really, still, my for loop is running like mad!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

recv should block by default, unless there's a socket error or you explicitly set the socket to non-blocking. Be sure to check the return value for error. For more information see the Microsofts MSDN article on recv.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...