accept()函数充当非阻塞

时间:2013-04-12 13:32:53

标签: c++ sockets winsock

我正在使用等待客户端连接的Winsock编写服务器程序。代码是这样的:

#include <winsock.h>
#pragma comment(lib, "wsock32.lib")

WSADATA wsaData;
WSAStartup(0x101, &wsaData);
SOCKET listeningSocket;
listeningSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

SOCKADDR_IN serverInfo;
serverInfo.sin_family = AF_INET;
serverInfo.sin_addr.s_addr = INADDR_ANY;
serverInfo.sin_port = htons(80);

bind(listeningSocket, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr));
listen(listeningSocket, 5);

SOCKET theClient;
while(true)
{
    theClient = accept(listeningSocket,NULL,NULL);
    ....
    recv(theClient,Message,strlen(Message),0);
    ....
    ....
}

我遇到的问题是服务器不等待客户端并在accept()函数之后继续执行。具体来说,accept()函数不会阻止执行。

2 个答案:

答案 0 :(得分:1)

您应该检查所有库函数的返回值。可能是早期调用(例如bind())失败,但您永远不会发现,因为您忽略了返回值。

答案 1 :(得分:0)

尝试在接受时打印出错误消息,它可能有助于解决您遇到的问题(您也应该使用bind执行此操作。)

绑定错误检查:

int result; 
result = bind(listeningSocket, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr));
if (result == SOCKET_ERROR) {
    printf("bind failed with error: %d\n", WSAGetLastError());
    freeaddrinfo(serverInfo);
    closesocket(listeningSocket);
    WSACleanup();
    return 1;
}

接受错误检查:

theClient = INVALID_SOCKET;

// Accept a client socket
theClient = accept(listeningSocket, NULL, NULL);
if (theClient == INVALID_SOCKET) {
    printf("accept failed: %d\n", WSAGetLastError());
    closesocket(listeningSocket);
    WSACleanup();
    return 1;
}

了解更多信息,请查看:

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

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