我在 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>
它不起作用(无效的套接字),如果我没有,它工作得很好。我做错了什么?
谢谢!