套接字不接受连接

时间:2013-08-19 12:10:46

标签: c++ visual-studio-2005

我有一个服务器套接字接受客户端套接字连接。接受是一个线程

套接字创建

int ServerSocket::CreateSocket(int port)
{
listenfd = 0;
struct sockaddr_in serv_addr; 
unsigned long iMode = 1;

listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port); 


ioctlsocket(listenfd, FIONBIO, &iMode);

if (bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
    return 0;
}

if (listen(listenfd, 20) < 0)
{
    return 0;
}

return listenfd;
}

套接字接受

void ServerSocket::AcceptClients_1(void * p)
{
struct sockaddr_in  cli_addr;

// get a pointer to the ServerSocket object
ServerSocket * pThis = (ServerSocket *)p;
int iResult, cli_len;
cli_len = sizeof(cli_addr);
struct timeval tv = { 0, 1000 };  
SOCKET s = pThis->GetSocket();
fd_set rfds;

FD_ZERO(&rfds);
FD_SET(s, &rfds);

while (!pThis->ShutDownRequested)
{
   iResult = select(s+1, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
   if(iResult > 0)
   {
         // never comes here
         SOCKET sclient =  accept(s, (struct sockaddr *)&cli_addr, 
                            &cli_len);
    }
   else if (iResult == 0)   /// timeout
   {
        continue;
   }
   // error comes here are going to accept 2nd time
   DWORD dwError = GetLastError();
   return;
 }  
}

代码来自select()。第一次返回0,但第二次总是返回-1,错误10022.我不明白为什么。请帮忙。

2 个答案:

答案 0 :(得分:0)

iResult = 0并不总是意味着超时,对于非阻塞套接字,您需要检查WSAGetLastError并处理一些错误代码,例如WSAEWOULDBLOCK意味着您需要在此套接字上等待下一个事件。

http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx

答案 1 :(得分:0)

确保pThis->GetSocket()正确返回listenfd。此外,您应在每次调用cli_len = sizeof(cli_addr);之前重新初始化accept(这是一个值结果参数)。