0

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

套接字创建

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。我不明白为什么。请帮忙。

4

2 回答 2

0

iResult=0 does not always mean timeout, for non-blocking sockets, you need to check WSAGetLastError and deal with some error codes, for example WSAEWOULDBLOCK means you need to wait next event on this socket.

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

于 2013-08-19T12:30:08.160 回答
0

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

于 2013-08-19T13:07:47.600 回答