我使用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>
它不起作用(无效套接字),如果我不这样做,它完美地工作..
我做错了什么?
谢谢!
答案 0 :(得分:1)
<thread>
中没有任何内容可以以任何方式影响winsock API。但为了以防万一,您需要预编译代码并查看预编译器的输出,或者只需使用调试器逐步执行代码,并确保所有变量和函数参数都具有您期望的正确值。
答案 1 :(得分:0)
我相信
#include <winsock2.h>
套接字需要。
#include <thread>
用于C ++ 11中的新线程支持,我相信它只在VC13或VC12中支持。