OSVR Framework (Internal Development Docs)  0.6-1962-g59773924
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
NetworkingSupport.cpp
Go to the documentation of this file.
1 
11 // Copyright 2015 Sensics, Inc.
12 //
13 // Licensed under the Apache License, Version 2.0 (the "License");
14 // you may not use this file except in compliance with the License.
15 // You may obtain a copy of the License at
16 //
17 // http://www.apache.org/licenses/LICENSE-2.0
18 //
19 // Unless required by applicable law or agreed to in writing, software
20 // distributed under the License is distributed on an "AS IS" BASIS,
21 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 // See the License for the specific language governing permissions and
23 // limitations under the License.
24 
25 // Internal Includes
27 #include <osvr/Util/WideToUTF8.h>
28 
29 // Library/third-party includes
30 // - none
31 
32 // Standard includes
33 #include <iostream>
34 #include <type_traits>
35 
36 #ifdef _WIN32
37 #define WIN32_LEAN_AND_MEAN
38 #include <winsock2.h>
39 
40 #endif
41 
42 namespace osvr {
43 namespace common {
44 
45 #ifdef _WIN32
46 
47  static inline std::string wsaErrorCodeToString(int err) {
48  TCHAR buf[256] = {0};
49 
50  FormatMessage(
51  FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
52  err, 0, &(buf[0]), sizeof(buf) / sizeof(buf[0]), nullptr);
53  return util::tcharToUTF8String(buf);
54  }
55 
56  inline bool NetworkingSupport::m_start() {
57  WSADATA wsaData;
58  auto status = WSAStartup(MAKEWORD(2, 2), &wsaData);
59  if (0 == status) {
60  m_up = true;
61  return true;
62  }
63  m_err = "WSAStartup failed: " + wsaErrorCodeToString(status);
64  return false;
65  }
66 
67  inline bool NetworkingSupport::m_stop() {
68  if (SOCKET_ERROR == WSACleanup()) {
69  m_err =
70  "WSACleanup failed: " + wsaErrorCodeToString(WSAGetLastError());
71  return false;
72  }
73  return true;
74  }
75 #else
76  // Don't think any other platforms need this.
77  inline bool NetworkingSupport::m_start() {
78  m_up = true;
79  return true;
80  }
81  inline bool NetworkingSupport::m_stop() { return true; }
82 #endif
83 
84  NetworkingSupport::NetworkingSupport() : m_up(false), m_success(true) {
85  m_success = m_start();
86  }
87 
89  shutdown();
90  if (!wasSuccessful()) {
91  std::cerr << getError() << std::endl;
92  }
93  }
94 
96  m_success = true;
97  m_err.clear();
98  if (m_up) {
99  m_success = m_stop();
100  }
101  }
102 } // namespace common
103 } // namespace osvr
void shutdown()
Shutdown before destruction.
std::string const & getError() const
Get error message, if any.
bool wasSuccessful() const
Get whether the last operation (automatic startup or manual, early shutdown) was successful.
Configured header for internal UTF16 or Windows TCHAR to UTF8 conversion. Using this header requires ...