6 #define WIN32_LEAN_AND_MEAN
18 #pragma comment(lib, "Ws2_32.lib")
19 #pragma comment(lib, "Mswsock.lib")
20 #pragma comment(lib, "AdvApi32.lib")
31 auto rv = WSAStartup(MAKEWORD(2, 2), &wsaData);
41 ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error,
42 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, (
sizeof(buf) /
sizeof(
char)), NULL);
61 return socket_ != INVALID_SOCKET;
76 void connect(
const std::string &host,
int port)
84 ZeroMemory(&hints,
sizeof(hints));
86 hints.ai_family = AF_INET;
87 hints.ai_socktype = SOCK_STREAM;
88 hints.ai_flags = AI_NUMERICSERV;
89 hints.ai_protocol = 0;
92 struct addrinfo *addrinfo_result;
93 auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result);
97 last_error = ::WSAGetLastError();
104 for (
auto *rp = addrinfo_result; rp !=
nullptr; rp = rp->ai_next)
106 socket_ = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
109 last_error = ::WSAGetLastError();
119 last_error = ::WSAGetLastError();
123 ::freeaddrinfo(addrinfo_result);
132 ::setsockopt(
socket_, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<char *
>(&enable_flag),
sizeof(enable_flag));
139 size_t bytes_sent = 0;
140 while (bytes_sent < n_bytes)
142 const int send_flags = 0;
143 auto write_result =
::send(
socket_,
data + bytes_sent, (
int)(n_bytes - bytes_sent), send_flags);
144 if (write_result == SOCKET_ERROR)
146 int last_error = ::WSAGetLastError();
151 if (write_result == 0)
155 bytes_sent +=
static_cast<size_t>(write_result);