From ff5f3f3abc57d14ad8daa7c79ceb7f70d7dc0764 Mon Sep 17 00:00:00 2001 From: KongQun Yang Date: Sat, 16 Nov 2019 22:17:17 -0800 Subject: [PATCH] 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 --- packager/file/udp_file.cc | 33 +++++++++------------------------ packager/file/udp_file.h | 4 ++++ 2 files changed, 13 insertions(+), 24 deletions(-) diff --git a/packager/file/udp_file.cc b/packager/file/udp_file.cc index f740f0a76f..d7fb03505c 100644 --- a/packager/file/udp_file.cc +++ b/packager/file/udp_file.cc @@ -66,6 +66,10 @@ bool UdpFile::Close() { socket_ = INVALID_SOCKET; } delete this; +#if defined(OS_WIN) + if (wsa_started_) + WSACleanup(); +#endif return true; } @@ -113,26 +117,6 @@ bool UdpFile::Tell(uint64_t* position) { 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 { public: explicit ScopedSocket(SOCKET sock_fd) : sock_fd_(sock_fd) {} @@ -158,12 +142,13 @@ class ScopedSocket { bool UdpFile::Open() { #if defined(OS_WIN) - static LibWinsockInitializer lib_winsock_initializer; - if (lib_winsock_initializer.error() != 0) { - LOG(ERROR) << "Winsock start up failed with error " - << lib_winsock_initializer.error(); + WSADATA wsa_data; + int wsa_error = WSAStartup(MAKEWORD(2, 2), &wsa_data); + if (wsa_error != 0) { + LOG(ERROR) << "Winsock start up failed with error " << wsa_error; return false; } + wsa_started_ = true; #endif // defined(OS_WIN) DCHECK_EQ(INVALID_SOCKET, socket_); diff --git a/packager/file/udp_file.h b/packager/file/udp_file.h index f8b5875b2a..039563abdb 100644 --- a/packager/file/udp_file.h +++ b/packager/file/udp_file.h @@ -47,6 +47,10 @@ class UdpFile : public File { private: SOCKET socket_; +#if defined(OS_WIN) + // For Winsock in Windows. + bool wsa_started_ = false; +#endif // defined(OS_WIN) DISALLOW_COPY_AND_ASSIGN(UdpFile); };