0

我在 Microsoft MSDN 的帮助下编写了一个服务器......

它与我的客户完美配合,连接和一切,但是当我添加 -

#include <thread>

简单地这一行到我的项目,它使服务器停止工作(绑定/监听时总是得到无效的套接字)......

这是我的代码:

SOCKET Connect_To_Client()
{
     // Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

int count = 0;
while (iResult != NO_ERROR) 
{
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    count++;

    if (count == 3)
    {
        MessageBox(NULL, "WSA Startup failed!", "ERROR", MB_OK);
        return -1;
    }


}

// Create a SOCKET for listening for incoming connection requests.
SOCKET ListenSocket;
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

count = 0;
while (ListenSocket == INVALID_SOCKET) 
{
    ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    count++;

    if (count == 3)
    {
        MessageBox(NULL, "Error in Listening Socket!", "ERROR", MB_OK);
        closesocket(ListenSocket);
        WSACleanup();
        return -1;
    }
}

//ADDR
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(DEFAULT_IP);
service.sin_port = htons(DEFAULT_PORT);

count = 0;
bind(ListenSocket, (SOCKADDR *) & service, sizeof (service));

// Listen for incoming connection requests on the created socket
count = 0;
cout << "Listening..." << endl;
while (listen(ListenSocket, 1) == SOCKET_ERROR) 
{
    count++;

    if (count == 3)
    {
        MessageBox(NULL, "Error listening!", "ERROR", MB_OK);
        closesocket(ListenSocket);
        WSACleanup();
        return -1;
    }
}

SOCKET AcceptSocket; // Create a SOCKET for accepting incoming requests.

// Accept the connection.
AcceptSocket = accept(ListenSocket, NULL, NULL);

count = 0;
while(AcceptSocket == INVALID_SOCKET) 
{
    AcceptSocket = accept(ListenSocket, NULL, NULL);
    count++;

    if (count == 3)
    {
        MessageBox(NULL, "Error Connecting", "ERROR", MB_OK);
        closesocket(ListenSocket);
        WSACleanup();
        return -1;
    }
}

cout << "Connected!" << endl;
return AcceptSocket;
}

如果我有#include <thread>它不起作用(无效的套接字),如果我没有,它工作得很好。我做错了什么?

谢谢!

4

2 回答 2

1

没有任何东西<thread>应该以任何方式影响winsock API。但以防万一,您需要预编译代码并查看预编译器的输出,或者只需使用调试器单步调试代码,并确保所有变量和函数参数都具有您期望的正确值。

于 2013-10-30T20:08:56.243 回答
0

我相信

#include <winsock2.h>

插座是必需的。这

#include <thread>

用于 C++11 中的新线程支持,我相信它仅在 VC13 或 VC12 中受支持。

于 2013-10-30T20:11:21.650 回答