我正在尝试为学校项目创建多线程服务器,并且我依赖于我过去编写的类似代码,但是由于某种原因,在open
函数中,该代码始终进入if
语句并崩溃。
是什么阻止了它创建套接字?
#pragma comment(lib, "Ws2_32.lib")
#include <WinSock2.h>
#include <exception>
#include <iostream>
#include <string>
#include <numeric>
#include <deque>
#include <queue>
#include <mutex>
#include <condition_variable>
void accept();
void open();
void close();
void bindAndListen();
#ifdef _DEBUG
#include <stdio.h>
#define TRACE(msg, ...) printf(msg "\n", __VA_ARGS__);
#else
#define TRACE(msg, ...) printf(msg "\n", __VA_ARGS__);
#define TRACE(msg, ...)
#endif
static const unsigned short PORT = 8826;
static const unsigned int IFACE = 0;
SOCKET _socket;
void clientHandler(SOCKET client_socket);
void close();
int main()
{
open();
}
void bindAndListen()
{
struct sockaddr_in sa = { 0 };
sa.sin_port = htons(PORT);
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = IFACE;
if (bind(_socket, (struct sockaddr*) & sa, sizeof(sa)) == SOCKET_ERROR)
throw std::exception(__FUNCTION__ " - bind");
TRACE("binded");
if (listen(_socket, SOMAXCONN) == SOCKET_ERROR)
throw std::exception(__FUNCTION__ " - listen");
TRACE("listening...");
}
void clientHandler(SOCKET client_socket)
{
std::cout << "hello";
}
void close()
{
TRACE(__FUNCTION__ " closing accepting socket");
try
{
closesocket(_socket);
}
catch (...) {}
}
void open()
{
_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (_socket == INVALID_SOCKET)
throw std::exception(__FUNCTION__ " - socket");
}
void accept()
{
SOCKET client_socket = accept(_socket, NULL, NULL);
if (client_socket == INVALID_SOCKET)
throw std::exception(__FUNCTION__);
TRACE("Client accepted !");
// create new thread for client and detach from it
std::thread tr(&clientHandler, _socket);
tr.detach();
}
最佳答案
您应该调用WSAGetLastError来获取导致返回INVALID_SOCKET的实际错误代码。
在这种情况下,您似乎没有调用WSAStartup,因此收到了WSANOTINITIALISED错误。
使用任何Winsock函数之前,必须先调用WSAStartup。