这是socket程序的服务器端,源程序如下:
int main(int argc, _TCHAR* argv[])
{
WSADATA              wsaData;
SOCKET               ListeningSocket;
    SOCKET               NewConnection;
    SOCKADDR_IN          ServerAddr;
    SOCKADDR_IN          ClientAddr;
int                  ClientAddrLen;
    int                  Port = 5150;
char                 buff[1024];
   // Initialize Winsock version 2.2
   int Ret;
   if ((Ret = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0)
   {
      printf("WSAStartup failed with error %d\n", Ret);
      return 1;
   }
   
   // Create a new socket to listen for client connections.
 
      ListeningSocket = socket(AF_INET, SOCK_STREAM, 0);
  
      ServerAddr.sin_family = AF_INET;
      ServerAddr.sin_port = htons(Port);    
      ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);    // Associate the address information with the socket using bind.
  
      bind(ListeningSocket, (SOCKADDR *)&ServerAddr, 
      sizeof(ServerAddr));   // Listen for client connections. We used a backlog of 5, which
   // is normal for many applications.      if(listen(ListeningSocket, 5)==SOCKET_ERROR)
  {
  return 1;
  }
      printf("Accepting connections..\n");
   // Accept a new connection when one arrives.      NewConnection =accept(ListeningSocket, (SOCKADDR *)  & ClientAddr,& ClientAddrLen);
      recv(NewConnection,buff,1024,0);
      printf("received from client:%s\n",buff);      
      closesocket(NewConnection);
      closesocket(ListeningSocket);
   if (WSACleanup() == SOCKET_ERROR)
   {
      printf("WSACleanup failed with error %d\n", WSAGetLastError());
   } return 0;
}
问题是没有客户端请求连接时,这句:
NewConnection =accept(ListeningSocket, (SOCKADDR *)  & ClientAddr,& ClientAddrLen);
应该是阻塞的,但是我的程序运行时,直接运行到这句以下了,退出来了,为什么啊

解决方案 »

  1.   

    NewConnection的值一直是INVALID_SOCKET,
    好像这个accept()函数不是阻塞的,不知道为什么
      

  2.   

    看看
    bind(ListeningSocket, (SOCKADDR *)&ServerAddr, 
          sizeof(ServerAddr));有没有成功
      

  3.   

    端口有没有占用,socket和bind两句你没有出错判断,跟踪这两句的返回值,socket返回>0是正确的,bind返回等于0是正确的.
      

  4.   

    ListeningSocket = socket(AF_INET, SOCK_STREAM, 0);
    bind(ListeningSocket, (SOCKADDR *)&ServerAddr, 
          sizeof(ServerAddr));
    NewConnection =accept(ListeningSocket, (SOCKADDR *)  & ClientAddr,& ClientAddrLen);
    ===============================
    这些不判断返回值???在调用有返回值的函数的时候,不检查返回值 不是编程的好习惯,一个程序员不应该这么做!
      

  5.   

    各位大哥,我查过

    ListeningSocket = socket(AF_INET, SOCK_STREAM, 0);
    bind(ListeningSocket, (SOCKADDR *)&ServerAddr,
    sizeof(ServerAddr));
    NewConnection =accept(ListeningSocket, (SOCKADDR *) & ClientAddr,& ClientAddrLen);
    的返回值,前两个正常,NewConnection是INVALID_SOCKET
      

  6.   

    bind()的返回值是0
    ListeningSocket的值是2976
    NewConnection的值是4294967295
      

  7.   


    你的ClientAddrLen没有初始化,改成即可:int ClientAddrLen = sizeof(ClientAddr);
    应该可以结帖了,呵呵