cleanup tcp client WSA Startup/Shutdown

This commit is contained in:
gabime 2021-09-05 17:28:28 +03:00
parent dd10e41b27
commit f97dcc72dc

View File

@ -25,20 +25,6 @@ class tcp_client
{ {
SOCKET socket_ = INVALID_SOCKET; SOCKET socket_ = INVALID_SOCKET;
static bool winsock_initialized_()
{
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
{
return false;
}
else
{
closesocket(s);
return true;
}
}
static void init_winsock_() static void init_winsock_()
{ {
WSADATA wsaData; WSADATA wsaData;
@ -59,6 +45,18 @@ class tcp_client
} }
public: public:
tcp_client()
{
init_winsock_();
}
~tcp_client()
{
close();
::WSACleanup();
}
bool is_connected() const bool is_connected() const
{ {
return socket_ != INVALID_SOCKET; return socket_ != INVALID_SOCKET;
@ -68,7 +66,6 @@ public:
{ {
::closesocket(socket_); ::closesocket(socket_);
socket_ = INVALID_SOCKET; socket_ = INVALID_SOCKET;
WSACleanup();
} }
SOCKET fd() const SOCKET fd() const
@ -76,20 +73,10 @@ public:
return socket_; return socket_;
} }
~tcp_client()
{
close();
}
// try to connect or throw on failure // try to connect or throw on failure
void connect(const std::string &host, int port) void connect(const std::string &host, int port)
{ {
// initialize winsock if needed
if (!winsock_initialized_())
{
init_winsock_();
}
if (is_connected()) if (is_connected())
{ {
close(); close();