Call WSAStartup once for every new socket

Some users are seeing problems with only one WSAStartup call.

WSAStartup can be called more than once:
https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsastartup

Fixes #643.

Change-Id: I81e0e7979d6a586da452984a96a8557b7b3ce7f6
This commit is contained in:
KongQun Yang 2019-11-16 22:17:17 -08:00
parent 0b53b40428
commit ff5f3f3abc
2 changed files with 13 additions and 24 deletions

View File

@ -66,6 +66,10 @@ bool UdpFile::Close() {
socket_ = INVALID_SOCKET; socket_ = INVALID_SOCKET;
} }
delete this; delete this;
#if defined(OS_WIN)
if (wsa_started_)
WSACleanup();
#endif
return true; return true;
} }
@ -113,26 +117,6 @@ bool UdpFile::Tell(uint64_t* position) {
return false; return false;
} }
#if defined(OS_WIN)
class LibWinsockInitializer {
public:
LibWinsockInitializer() {
WSADATA wsa_data;
error_ = WSAStartup(MAKEWORD(2, 2), &wsa_data);
}
~LibWinsockInitializer() {
if (error_ == 0)
WSACleanup();
}
int error() const { return error_; }
private:
int error_;
};
#endif // defined(OS_WIN)
class ScopedSocket { class ScopedSocket {
public: public:
explicit ScopedSocket(SOCKET sock_fd) : sock_fd_(sock_fd) {} explicit ScopedSocket(SOCKET sock_fd) : sock_fd_(sock_fd) {}
@ -158,12 +142,13 @@ class ScopedSocket {
bool UdpFile::Open() { bool UdpFile::Open() {
#if defined(OS_WIN) #if defined(OS_WIN)
static LibWinsockInitializer lib_winsock_initializer; WSADATA wsa_data;
if (lib_winsock_initializer.error() != 0) { int wsa_error = WSAStartup(MAKEWORD(2, 2), &wsa_data);
LOG(ERROR) << "Winsock start up failed with error " if (wsa_error != 0) {
<< lib_winsock_initializer.error(); LOG(ERROR) << "Winsock start up failed with error " << wsa_error;
return false; return false;
} }
wsa_started_ = true;
#endif // defined(OS_WIN) #endif // defined(OS_WIN)
DCHECK_EQ(INVALID_SOCKET, socket_); DCHECK_EQ(INVALID_SOCKET, socket_);

View File

@ -47,6 +47,10 @@ class UdpFile : public File {
private: private:
SOCKET socket_; SOCKET socket_;
#if defined(OS_WIN)
// For Winsock in Windows.
bool wsa_started_ = false;
#endif // defined(OS_WIN)
DISALLOW_COPY_AND_ASSIGN(UdpFile); DISALLOW_COPY_AND_ASSIGN(UdpFile);
}; };