1

我正在使用等待客户端连接的 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() 函数不会阻塞执行。

4

2 回答 2

1

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

于 2013-04-12T13:36:06.307 回答
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

于 2013-04-12T13:45:09.440 回答