32 #pragma comment(lib, "Ws2_32.lib") 34 #define DEFAULT_PORT "11411" 49 void init (
char *server_hostname)
52 int result = WSAStartup (MAKEWORD (2, 2), &wsaData);
56 std::cerr <<
"Could not initialize windows socket (" << result <<
")" << std::endl;
70 freeaddrinfo (servers);
74 std::cerr <<
"Could not connect to server" << std::endl;
82 int result = recv (
mySocket, &data, 1, 0);
85 if (WSAEWOULDBLOCK != WSAGetLastError())
87 std::cerr <<
"Failed to receive data from server " << WSAGetLastError() << std::endl;
93 std::cerr <<
"Connection to server closed" << std::endl;
96 return (
unsigned char) data;
99 void write (
const unsigned char *data,
int length)
101 int result = send (
mySocket, (
const char *) data, length, 0);
102 if (SOCKET_ERROR == result)
104 std::cerr <<
"Send failed with error " << WSAGetLastError () << std::endl;
113 GetSystemTime (&st_now);
114 unsigned long millis = st_now.wHour * 3600000 +
115 st_now.wMinute * 60000 +
116 st_now.wSecond * 1000 +
117 st_now.wMilliseconds;
132 struct addrinfo *ai_output = NULL;
133 struct addrinfo ai_input;
136 int c = hostname.find_last_of (
':');
137 string host = hostname.substr (0, c);
138 string port = (c < 0) ?
DEFAULT_PORT : hostname.substr (c + 1);
140 ZeroMemory (&ai_input,
sizeof (ai_input));
141 ai_input.ai_family = AF_UNSPEC;
142 ai_input.ai_socktype = SOCK_STREAM;
143 ai_input.ai_protocol = IPPROTO_TCP;
146 result = getaddrinfo (host.c_str (), port.c_str (), &ai_input, &ai_output);
149 std::cerr <<
"Could not resolve server address (" << result <<
")" << std::endl;
162 for (
struct addrinfo * ptr = servers; ptr != NULL; ptr = ptr->ai_next)
164 mySocket = socket (ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
167 std::cerr <<
"Could not great socket " << WSAGetLastError ();
171 result = connect (
mySocket, ptr->ai_addr, (
int) ptr->ai_addrlen);
172 if (SOCKET_ERROR == result)
185 setsockopt (
mySocket, IPPROTO_TCP, TCP_NODELAY, &value,
sizeof (value));
188 result = ioctlsocket (
mySocket, FIONBIO, &iMode);
191 std::cerr <<
"Could not make socket nonblocking " << result << std::endl;
208 impl->init (server_hostname);
213 return impl->read ();
218 impl->write (data, length);
223 return impl->time ();
struct addrinfo * get_server_addr(const string &hostname)
void init(char *server_hostname)
void init(char *server_hostname)
void connect_to_server(struct addrinfo *servers)
void write(const unsigned char *data, int length)
void write(const unsigned char *data, int length)