接收到client端的connect后,server端为每个client的winsocket分配一个线程,在线程内部使用select函数来检测该winsocket是否可读。
当client端断开winsocket后,再连接,出现10048(地址在使用中)的错误导致连接失败,可是过一会(大概5分钟)再来连,就连上了,怎么回事啊,该怎么样才能够每次都能连上??

解决方案 »

  1.   

    代码的逻辑错误,诸如状态错误,资源没有释放之类的问题。跟select没什么关系
      

  2.   

    //====================================================================
    // 函数功能: select 线程, 可读, 发送 消息 UM_READABILITY
    //====================================================================
    DWORD WINAPI SelectThread(LPVOID pParam)
    {
    if(pParam == NULL)
    {
    #ifdef _DEBUG
    ::MessageBox(NULL, "结束 select thread !", "Message Box", MB_OK); 
    #endif
    return 0;
    }
    //得到传递的参数
    CMySocket * pSocket = (CMySocket *)pParam;

    int             n;
    fd_set readfds;
    SOCKET socket;
    struct timeval Timeval; Timeval.tv_sec  = 0;
    Timeval.tv_usec = 10;

    socket = pSocket->GetSocket(); //进入无限循环,直到主线程结束
    while(true)
    {
    if(::g_bOverThread == true)
    {
    #ifdef _DEBUG
    //::MessageBox(NULL, "结束 select thread !", "Message Box", MB_OK); 
    #endif
    //??????
    //pSocket->Close();
    return 1;
    }
    DWORD word = ::WaitForSingleObject(::g_handle, 0);
    if(word == WAIT_OBJECT_0) //g_handle is signaled
    {
    #ifdef _DEBUG
    //::MessageBox(NULL, "结束 select thread !", "Message Box", MB_OK); 
    #endif
    //??????
    ::MessageBox(NULL,"recv shutdown","Message Box",MB_OK);
    pSocket->Close();
    return 1;
    }
    if(socket != 0)
    {
    FD_ZERO(&readfds);
    FD_SET(socket, &readfds);

    n = ::select(0, &readfds, NULL, NULL, &Timeval);
    if(n == SOCKET_ERROR)
    {
    #ifdef _DEBUG
    ::MessageBox(NULL, "Select 失败 !", "Messsage Box", MB_OK);
    #endif
    return 0;
    }
    if(n > 0)
    {
    if(FD_ISSET(socket, &readfds))
    {
    //{{可读, 发送消息 UM_READABILITY
    CChat_ServerApp * pwnd = (CChat_ServerApp *)::AfxGetApp();
    #if 1
    ::SendMessage(pwnd->m_pMainWnd->m_hWnd, 
              UM_READABILITY, 
      (WPARAM)pSocket, 
      NULL);
    #else
    ::PostMessage(pwnd->m_pMainWnd->m_hWnd, 
              UM_READABILITY, 
      (WPARAM)pSocket, 
      NULL);
    #endif
    //}}可读, 发送消息 UM_READABILITY
    }
    }
    }
    }
    }以上我的程序中server端的select线程,注释???的地方是销毁socket,看看是什么错误?