1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
ClientNetwork::ClientNetwork( void )
{
// create WSADATA object
WSADATA wsaData;
// socket
ClientSocket = INVALID_SOCKET;
initMode = 1;
// holds address info for socket to connect to
struct addrinfo * result = NULL, * ptr = NULL, hints;
// Initialize Winsock
try {
(( initResult = WSAStartup( MAKEWORD( 2, 2 ), & wsaData ) ) > 0 ? throw initResult
: false );
} catch( int e ) {
cout << "Blad WSAStartup: " << e << endl;
exit( 1 );
}
// set address info
ZeroMemory( & hints, sizeof( hints ) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
//resolve server address and port
try {
(( initResult = getaddrinfo( "127.0.0.1", DEFAULT_PORT, & hints, & result ) ) > 0 ? throw initResult
: false );
} catch( int e ) {
cout << "Blad Addrinfo: " << e << endl;
WSACleanup();
exit( 1 );
}
// Attempt to connect to an address until one succeeds
for( ptr = result; ptr != NULL; ptr = ptr->ai_next ) {
try {
(( ClientSocket = socket( ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol ) ) == INVALID_SOCKET ? throw INVALID_SOCKET
: false );
} catch(...) {
cout << "Blad Socket'a: " << WSAGetLastError() << endl;
WSACleanup();
exit( 1 );
}
// Connect to server.
try {
(( initResult = connect( ClientSocket, ptr->ai_addr,( int ) ptr->ai_addrlen ) ) == SOCKET_ERROR ? throw initResult
: false );
} catch(...) {
closesocket( ClientSocket );
ClientSocket = INVALID_SOCKET;
cout << "Serwer wylaczony!" << endl;
}
}
// no longer need address info for server
freeaddrinfo( result );
if( ClientSocket == INVALID_SOCKET )
{
cout << "Nie mozna polaczyć sie z serwerem!" << endl;
WSACleanup();
exit( 1 );
}
// Set the mode of the socket to be nonblocking
try {
(( initResult = ioctlsocket( ClientSocket, FIONBIO, & initMode ) ) == SOCKET_ERROR ? throw initResult
: false );
} catch(...) {
cout << "Blad ioctlsocket: " << WSAGetLastError() << endl;
closesocket( ClientSocket );
WSACleanup();
exit( 1 );
}
}
|